﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.JsonPatch.Operations;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.CG;
using NP.BPMReportPlatform.CG.Dto;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Entities.BPM_Process;
using NP.BPMReportPlatform.Holiday.Dto;
using NP.BPMReportPlatform.HR.Dto;
using NP.BPMReportPlatform.MaterialMasterData;
using NP.BPMReportPlatform.MaterialMasterData.Dto;
using NP.BPMReportPlatform.Utilities;
using NP.BPMReportPlatform.Utils;
using NP.Enterprise.Utils.Http;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Volo.Abp.ObjectMapping;
using Volo.Abp.Users;

namespace NP.BPMReportPlatform.FrameOrder
{
    public class MMDOrderService : BPMReportPlatformAppService, IMMDOrderService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform, _dbProcess;
        private readonly SqlSugarClient _dbEngine;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        private readonly INPRestHttpHelper _nPRestHttp;
        private readonly IExcelImporter _importer;

        public MMDOrderService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp
            , IBPMPlatformAppService iBPMPlatformApp, INPRestHttpHelper nPRestHttp, IConfiguration configuration, IExcelImporter importer)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _dbProcess = sqlSugarAppService.GetProcessInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
            _nPRestHttp = nPRestHttp;
            _importer = importer;
        }

        #region 立才中心认证需求管理流程报表
        public async Task<PagedResultDto<GetLCZXRZXQGLOutput>> GetAllAsync(LCZXRZXQGLInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);
                //x.OrderStatus = GetInstanceType(x.InstanceNumber);
            });
            //返回结果
            return new PagedResultDto<GetLCZXRZXQGLOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetLCZXRZXQGLOutput>> ExportAsync(LCZXRZXQGLInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        /// <summary>
        /// 获取Queryable(报表展现)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<GetLCZXRZXQGLOutput> GetQueryable(LCZXRZXQGLInput input)
        {
            //业务需求，以下都属于处理中
            //if (!input.OrderStatus.IsNullOrEmpty() && SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), "处理中"))
            //{
            //    input.OrderStatus.Add("退回发起人（直接提交退回人）");
            //    input.OrderStatus.Add("退回发起人（逐级提交）");
            //    input.OrderStatus.Add("发起人撤回");
            //}
            var listQueryable = _db.Queryable<LCZXRZXQGLHeader, LCZXRZXQGLDetail, BusinessProcessesNew, LCZXRZXQGLConfig>(
                    (x, m, bu, c) => new JoinQueryInfos(
                        JoinType.Left, x.InstanceNumber == m.InstanceNumber, 
                        JoinType.Left, x.InstanceNumber == bu.InstanceId,
                        JoinType.Left, m.ConfigId == c.Id.ToString()))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), (x, m, bu, c) => x.InstanceNumber.Contains(input.InstanceNumber))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, m, bu, c) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), bu.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), (x, m, bu, c) => bu.StartUserName.Equals(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, (x, m, bu, c) => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)
                .Select((x, m, bu, c) =>
                    new GetLCZXRZXQGLOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        CreateTime = x.AddTime,
                        AddUserName = bu.StartUserName,
                        CourseName = x.CourseName,
                        CourseCode = x.CourseCode,
                        StartTime = x.StartTime,
                        EndTime = x.EndTime,
                        StudentNumber = x.StudentNumber,
                        TrainSchool = x.TrainSchool,
                        TrainDays = x.TrainDays,
                        StudentName = m.StudentName,
                        Gender = m.Gender,
                        ContractDetail = m.ContractDetail,
                        IdCardNumber = m.IdCardNumber,
                        AreaString = m.AreaString,
                        CertificateType = SqlFunc.IsNullOrEmpty(c.CertificateType) ? m.CertificateType : c.CertificateType,
                        CertificateName = SqlFunc.IsNullOrEmpty(c.NipponCertification) ? m.CertificateName : c.NipponCertification,
                        Grade = m.Grade,
                        CertificateEffect = SqlFunc.IsNullOrEmpty(c.Effect) ? m.CertificateEffect : c.Effect,
                        CertificateNumber = m.CertificateNumber,
                        CertificateDate = m.CertificateDate,
                        SpecialtyStoreAuthorizationNumber = m.SpecialtyStoreAuthorizationNumber,
                        SpecialtyStoreAuthorizationAddress = m.SpecialtyStoreAuthorizationAddress,
                        SpecialtyStoreAuthorizationPhone = m.SpecialtyStoreAuthorizationPhone,
                        CareerStartTime = m.CareerStartTime,
                        OrderStatus = bu.ProcessStatusName ?? "",
                        IsNation = m.IsNation,
                        TypeOfWork = SqlFunc.IsNullOrEmpty(c.TypeOfWork) ? m.TypeOfWork : c.TypeOfWork,
                        CapabilityLabel = SqlFunc.IsNullOrEmpty(c.CapabilityLabel) ? m.CapabilityLabel : c.CapabilityLabel,
                        TheoreticalScore = m.TheoreticalScore,
                        PracticalScore = m.PracticalScore,
                        RegionArea = m.RegionArea,
                        RegionCompany = m.RegionCompany,
                    }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);
            return listQueryable;
        }

        public async Task<PagedResultDto<GetLCZXRZXQGLNCOutput>> GetAllAsync(LCZXRZXQGLNCInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            //返回结果
            return new PagedResultDto<GetLCZXRZXQGLNCOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 国家证书 导出
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetLCZXRZXQGLNCOutput>> ExportAsync(LCZXRZXQGLNCInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        /// <summary>
        /// 获取Queryable(国家认证)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<GetLCZXRZXQGLNCOutput> GetQueryable(LCZXRZXQGLNCInput input)
        {
            var listQueryable = _db.Queryable<LCZXRZXQGLDetail>()
                .Where(x => x.InstanceNumber == null)
                .WhereIF(!string.IsNullOrWhiteSpace(input.StudentName), (x) => x.StudentName.Contains(input.StudentName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.IdCardNumber), (x) => x.IdCardNumber == input.IdCardNumber)
                .WhereIF(!string.IsNullOrWhiteSpace(input.CertificateType), (x) => x.CertificateType.Contains(input.CertificateType))
                .Where(x => x.IsNation && x.IsPublic)
                .Select(x => new GetLCZXRZXQGLNCOutput
                {
                    Id = x.Id,
                    AddTime = x.AddTime,
                    AddTimeStr = x.AddTime.ToString(DateFormatHelper.DateFormat),
                    StudentName = x.StudentName,
                    IdCardNumber = x.IdCardNumber,
                    CertificateType = x.CertificateType,
                    TypeOfWork = x.TypeOfWork,
                    IssuingUnit = x.IssuingUnit,
                    CertificateNumber = x.CertificateNumber,
                    CertificateDate = x.CertificateDate,
                    CertificateDateStr = x.CertificateDate != null && x.CertificateDate != DateTime.MinValue ? x.CertificateDate.Value.ToString(DateFormatHelper.DateFormat) : "",
                    PracticalScore = Convert.ToInt32(x.PracticalScore).ToString(),
                    TheoreticalScore = Convert.ToInt32(x.TheoreticalScore).ToString(),
                }).MergeTable().Distinct().OrderBy(x => x.AddTime, OrderByType.Desc);

            return listQueryable;
        }

        /// <summary>
        /// 国家证书 导入Excel
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public async Task<ImportResultExt<ImportLCZXInput>> ImporterLCZXExcel(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            var rst = await _importer.Import<ImportLCZXInput>(stream);
            var importData = rst.Data;
            if (!rst.HasError)
            {
                // 业务数据处理
                var dataList = _db.Queryable<LCZXRZXQGLDetail>().Where(x => x.IsNation).ToList();
                List<LCZXRZXQGLDetail> addList = new(); // 新增的证书集合
                List<LCZXRZXQGLDetail> editList = new(); // 更新的证书集合
                foreach (var item in importData)
                {
                    //验证BPM数据用户姓名和身份证是否有不一致的情况
                    var diffDetail = dataList.FirstOrDefault(x => x.IdCardNumber == item.IdCardNumber.Trim() && x.StudentName != item.StudentName.Trim());
                    if (diffDetail != null)
                    {
                        rst.Exception = new Exception("学员姓名:" + item.StudentName + " 与系统学员姓名:" + diffDetail.StudentName + "不一致！");
                        break;
                    }
                    var updateData = dataList.FirstOrDefault(x => x.IdCardNumber == item.IdCardNumber.Trim() && x.CertificateType == item.CertificateType);
                    if (updateData == null)
                    {
                        var insertData = new LCZXRZXQGLDetail()
                        {
                            Id = Guid.NewGuid(),
                            AddTime = DateTime.Now,
                            StudentName = item.StudentName,
                            IdCardNumber = item.IdCardNumber,
                            CertificateType = item.CertificateType,
                            TypeOfWork = item.TypeOfWork,
                            IssuingUnit = item.IssuingUnit,
                            CertificateNumber = item.CertificateNumber,
                            CertificateName = item.CertificateType,
                            CertificateDate = (item.CertificateDate == "长期" || item.CertificateDate.IsNullOrWhiteSpace()) ? null : item.CertificateDate.ObjToNullDate(),
                            TheoreticalScore = item.TheoreticalScore.ObjToNullDecimal(),
                            PracticalScore = item.PracticalScore.ObjToNullDecimal(),
                            IsNation = true,
                            IsPublic = true,
                        };
                        addList.Add(insertData);
                    }
                    else
                    {
                        updateData.StudentName = item.StudentName;
                        updateData.IdCardNumber = item.IdCardNumber;
                        updateData.CertificateType = item.CertificateType;
                        updateData.TypeOfWork = item.TypeOfWork;
                        updateData.IssuingUnit = item.IssuingUnit;
                        updateData.CertificateNumber = updateData.CertificateNumber;
                        updateData.CertificateName = item.CertificateType;
                        updateData.CertificateDate = (item.CertificateDate == "长期" || item.CertificateDate.IsNullOrWhiteSpace()) ? null : item.CertificateDate.ObjToNullDate();
                        updateData.TheoreticalScore = item.TheoreticalScore.ObjToNullDecimal();
                        updateData.PracticalScore = item.PracticalScore.ObjToNullDecimal();
                        updateData.IsNation = true;
                        updateData.IsPublic = true;
                        editList.Add(updateData);
                    }
                }
                if (addList.Count > 0)
                {
                    await _db.Insertable(addList).ExecuteCommandAsync();
                }
                if (editList.Count > 0)
                {
                    await _db.Updateable(editList).ExecuteCommandAsync();
                }
            }
            var resp = new ImportResultExt<ImportLCZXInput>()
            {
                Data = importData,
                Exception = rst.Exception,
                RowErrors = rst.RowErrors,
                TemplateErrors = rst.TemplateErrors
            };
            return resp;
        }

        /// <summary>
        /// 编辑保存国家证书
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<string> EditNationalData(LCZXRZXQGLDetail input)
        {
            var currentUserId = (await _dbPlatform.Queryable<Users>().FirstAsync(x => x.WorkNumber.Equals(CurrentUser.UserName)))?.UserId;
            var userId = currentUserId.HasValue && currentUserId != Guid.Empty ? currentUserId.ToString() : "";
            if (input.Id != null && input.Id != Guid.Empty)
            {
                var updateData = await _db.Queryable<LCZXRZXQGLDetail>().FirstAsync(x => x.Id == input.Id);
                if (updateData != null)
                {
                    updateData.StudentName = input.StudentName;
                    updateData.IdCardNumber = input.IdCardNumber;
                    updateData.CertificateType = input.CertificateType;
                    updateData.TypeOfWork = input.TypeOfWork;
                    updateData.IssuingUnit = input.IssuingUnit;
                    updateData.CertificateNumber = input.CertificateNumber;
                    updateData.CertificateName = input.CertificateType;
                    updateData.CertificateDate = input.CertificateDate;
                    updateData.TheoreticalScore = input.TheoreticalScore.ObjToNullDecimal();
                    updateData.PracticalScore = input.TheoreticalScore.ObjToNullDecimal();
                    updateData.UpdateTime = DateTime.Now;
                    updateData.UpdateUserId = userId;
                    var result = await _db.Updateable(updateData).ExecuteCommandAsync();
                    if (result > 0)
                    {
                        return "修改成功";
                    }
                    else
                    {
                        return "修改失败";
                    }
                }
                else
                {
                    return "数据未找到";
                }
            }
            else
            {
                var insertData = new LCZXRZXQGLDetail()
                {
                    Id = Guid.NewGuid(),
                    AddTime = DateTime.Now,
                    StudentName = input.StudentName,
                    IdCardNumber = input.IdCardNumber,
                    CertificateType = input.CertificateType,
                    TypeOfWork = input.TypeOfWork,
                    IssuingUnit = input.IssuingUnit,
                    CertificateNumber = input.CertificateNumber,
                    CertificateName = input.CertificateType,
                    CertificateDate = input.CertificateDate,
                    TheoreticalScore = input.TheoreticalScore.ObjToNullDecimal(),
                    PracticalScore = input.TheoreticalScore.ObjToNullDecimal(),
                    AddUserId = userId,
                    IsNation = true,
                    IsPublic = true,
                };
                var result = await _db.Insertable(insertData).ExecuteCommandAsync();
                if (result > 0)
                {
                    return "新增成功";
                }
                else
                {
                    return "新增失败";
                }
            }
        }

        public async Task<bool> DeleteNationalData(Guid Id)
        {
            return await _db.Deleteable<LCZXRZXQGLDetail>(x => x.Id == Id && x.IsNation).ExecuteCommandHasChangeAsync();
        }

        #endregion


        private string GetInstanceType(string instanceId)
        {
            var state = string.Empty;
            var query = _dbEngine
                .Queryable<Instances, InstanceStates>((it, its) => it.InstanceId == its.InstanceId)
                .WhereIF(!string.IsNullOrEmpty(instanceId), (it, its) => it.Number == instanceId)
                .Select((it, its) => new
                {
                    state = its
                }).ToList();

            if (query.Any())
            {
                var s = query.First().state.Status;
                state = ConvertToQueryStatus((TaskCommonStatus)s);
            }

            return state;
        }

        private string ConvertToQueryStatus(TaskCommonStatus status, bool isInnerState = false)
        {
            string queryStatus;

            switch (status)
            {
                case TaskCommonStatus.RecallStart:
                    queryStatus = "待发起";
                    break;
                case TaskCommonStatus.Start:
                case TaskCommonStatus.ReStart:
                    queryStatus = "发起";
                    break;
                case TaskCommonStatus.Processing:
                    queryStatus = "处理中";
                    break;
                case TaskCommonStatus.RejectActivity:
                case TaskCommonStatus.RejectActivityDirect:
                case TaskCommonStatus.Handover:
                case TaskCommonStatus.ExtraAppend:
                case TaskCommonStatus.ExtraInsert:
                case TaskCommonStatus.SkippedWhenEmptyResolver:
                case TaskCommonStatus.SkippedWhenSameApprover:
                    queryStatus = isInnerState ? "已完成" : "处理中";
                    break;
                case TaskCommonStatus.Done:
                    queryStatus = "通过";
                    break;
                case TaskCommonStatus.Refused:
                    queryStatus = "拒绝";
                    break;
                case TaskCommonStatus.Canceled:
                case TaskCommonStatus.InterveneAddNode:
                case TaskCommonStatus.InterveneJumpNode:
                case TaskCommonStatus.InterveneChangeUsers:
                case TaskCommonStatus.InterveneReorder:
                case TaskCommonStatus.InterveneRemoveNode:
                    queryStatus = "终止";
                    break;
                case TaskCommonStatus.RejectStart:
                case TaskCommonStatus.RejectStartDirect:
                    queryStatus = "退回";
                    break;
                case TaskCommonStatus.Exception:
                    queryStatus = "有异常";
                    break;
                case TaskCommonStatus.RecallActivity:
                    queryStatus = "撤回";
                    break;
                default:
                    queryStatus = "待发起";
                    break;
            }

            return queryStatus;
        }
        #region 排课平台

        public async Task<PagedResultDto<GetPKBudgetDataOutput>> GetPKBudgetDataAllAsync(PKBudgetDataInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            totalCount = listQueryable.Count();
            int index = (input.PageIndex - 1) * input.PageSize;
            int size = input.PageSize;
            if ((input.PageIndex * input.PageSize) > totalCount)
            {
                size = totalCount - index;
            }
            var listViewDto = listQueryable.ToList().GetRange(index, size);

            //var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            var mapperList = ObjectMapper.Map<List<PKBudgetData>, List<GetPKBudgetDataOutput>>(listViewDto);
            //返回结果
            return new PagedResultDto<GetPKBudgetDataOutput>()
            {
                TotalCount = totalCount,
                Items = mapperList
            };
        }

        /// <summary>
        /// 排课平台预算数据 导出
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<PKBudgetDataOutput>> ExportPKBudgetDataAsync(PKBudgetDataInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();

            var mapperList = ObjectMapper.Map<List<PKBudgetData>, List<PKBudgetDataOutput>>(listViewDto);
            return mapperList;
        }

        /// <summary>
        /// 获取Queryable(报表展现)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<PKBudgetData> GetQueryable(PKBudgetDataInput input)
        {
            var listQueryable = _db.Queryable<PKBudgetData>()
                    .WhereIF(!string.IsNullOrWhiteSpace(input.Year), (x) => x.Year == input.Year)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.Month), (x) => x.Month == input.Month)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.SchoolName) && input.SchoolName != "全部", (x) => x.SchoolName == input.SchoolName)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.Area) && input.Area != "全部", (x) => x.Area == input.Area)
                     .OrderBy(x => int.Parse(x.Year)).OrderBy(x => int.Parse(x.Month));

            return listQueryable;
        }

        //public async Task<PagedResultDto<GetPKBudgetDataOutput>> GetPageQueryable(PKBudgetDataInput input)
        //{
        //    RefAsync<int> totalCount = 0;
        //    var res = await _db.Queryable<PKBudgetData>()
        //        .WhereIF(!string.IsNullOrWhiteSpace(input.Year), (x) => x.Year == input.Year)
        //             .WhereIF(!string.IsNullOrWhiteSpace(input.Month), (x) => x.Month == input.Month)
        //             .WhereIF(!string.IsNullOrWhiteSpace(input.SchoolName) && input.SchoolName != "全部", (x) => x.SchoolName == input.SchoolName)
        //        .Select(b => new GetPKBudgetDataOutput()
        //        {
        //            Id = b.Id,
        //            Year = b.Year,
        //            Month = b.Month,
        //            SchoolName=b.SchoolName,
        //            Budget = b.Budget.ToString(),
        //            Estimate = b.Estimate.ToString(),
        //            Practical = b.Practical.ToString(),
        //            CreateTime = b.CreateTime
        //        }).GroupBy(b=>b.Id).Distinct().OrderBy(b => b.CreateTime, OrderByType.Desc).ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
        //    return new PagedResultDto<GetPKBudgetDataOutput>()
        //    {
        //        TotalCount = totalCount,
        //        Items = res
        //    };
        //}

        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public async Task<ImportResultExt<ImportPKBudgetDataInput>> ImporterPKBudgetDataExcel(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            var rst = await _importer.Import<ImportPKBudgetDataInput>(stream);
            var importData = rst.Data;
            string errorString = string.Empty;
            string errorStr = string.Empty;
            if (!rst.HasError)
            {
                //验证是否有重复数据和错误数据

                // 业务数据处理
                var detail = _db.Queryable<PKBudgetData>().ToList();
                List<PKBudgetData> addList = new List<PKBudgetData>(); // 新增
                List<PKBudgetData> editList = new List<PKBudgetData>(); // 更新
                var user = _dbPlatform.Queryable<Users>().Where(p => p.WorkNumber == CurrentUser.UserName).Select(p => p).First();
                foreach (var item in importData)
                {
                    //获取学校code和区域，不在数据字典中维护则提醒
                    if (string.IsNullOrEmpty(item.Year) || string.IsNullOrEmpty(item.Month)
                        || string.IsNullOrEmpty(item.SchoolName) || string.IsNullOrEmpty(item.Budget))
                    {
                        errorStr = "年份,月份,培训认证中心/项目组,预算不能为空";
                        continue;
                    }
                    if (double.Parse(item.Budget) > 99999999.99)
                    {
                        errorStr = " 请输入正确预算数字,最大值为99999999.99，小数限制2位";
                        continue;
                    }
                    var keyValues = _db.Queryable<KeyValues>().Where(x => x.Name == item.SchoolName).Single();
                    if (keyValues != null)
                    {
                        string schoolCode = keyValues.Code;
                        string area = keyValues.ParentCode;
                        //根据年，月，学校判断重复数据，保留最新一条
                        var oldDetail = detail.Where(x => x.Year == item.Year && x.Month == item.Month && x.SchoolName == item.SchoolName).FirstOrDefault();
                        if (oldDetail != null)
                        {
                            item.OperationType = "2";
                            var ishave2 = editList.Where(x => x.Year == item.Year && x.Month == item.Month && x.SchoolName == item.SchoolName).ToList();
                            if (ishave2.Count >= 1)
                            {
                                errorStr += "年份" + item.Year + ",月份" + item.Month + ",培训认证中心/项目组" + item.SchoolName + "有重复数据，请检查";
                                continue;
                            }
                        }
                        else
                        {
                            item.OperationType = "1";
                            var ishave = addList.Where(x => x.Year == item.Year && x.Month == item.Month && x.SchoolName == item.SchoolName).ToList();
                            if (ishave.Count >= 1)
                            {
                                errorStr += "年份" + item.Year + ",月份" + item.Month + ",培训认证中心/项目组" + item.SchoolName + "有重复数据，请检查";
                                continue;
                            }
                        }
                        PKBudgetData PKBudgetData = new PKBudgetData();
                        if (item.OperationType == "1")
                        {
                            PKBudgetData.Id = Guid.NewGuid();
                            PKBudgetData.Year = item.Year;
                            PKBudgetData.Month = item.Month;
                            PKBudgetData.SchoolName = item.SchoolName;
                            PKBudgetData.SchoolCode = schoolCode;
                            PKBudgetData.Area = area;
                            PKBudgetData.Budget = item.Budget == "" || item.Budget == null ? 0 : decimal.Parse(item.Budget);
                            PKBudgetData.Estimate = item.Estimate == "" || item.Estimate == null ? 0 : decimal.Parse(item.Estimate);
                            PKBudgetData.Practical = item.Practical == "" || item.Practical == null ? 0 : decimal.Parse(item.Practical);
                            PKBudgetData.CreateTime = DateTime.Now;
                            PKBudgetData.CreateUser = user.UserName;
                            addList.Add(PKBudgetData);
                        }
                        else
                        {
                            PKBudgetData.Id = oldDetail.Id;
                            PKBudgetData.Year = item.Year;
                            PKBudgetData.Month = item.Month;
                            PKBudgetData.SchoolName = item.SchoolName;
                            PKBudgetData.Budget = item.Budget == "" || item.Budget == null ? 0 : decimal.Parse(item.Budget);
                            PKBudgetData.Estimate = item.Estimate == "" || item.Estimate == null ? 0 : decimal.Parse(item.Estimate);
                            PKBudgetData.Practical = item.Practical == "" || item.Practical == null ? 0 : decimal.Parse(item.Practical);
                            PKBudgetData.UpdateTime = DateTime.Now;
                            PKBudgetData.UpdateUser = user.UserName;
                            editList.Add(PKBudgetData);
                        }

                    }
                    else
                    {
                        errorString += item.SchoolName + " ";
                        continue;
                    }

                }
                if (!string.IsNullOrEmpty(errorString) || !string.IsNullOrEmpty(errorStr))
                {
                    if (!string.IsNullOrEmpty(errorString))
                    {
                        errorString = errorString + "不在数据字典中无法添加或修改,联系管理员维护";
                    }
                    errorString = errorStr + errorString;
                }
                else
                {

                    if (addList.Count > 0)
                    {
                        await _db.Insertable(addList).ExecuteCommandAsync();
                    }
                    if (editList.Count > 0)
                    {
                        await _db.Updateable(editList).ExecuteCommandAsync();
                    }
                }
            }

            var resp = new ImportResultExt<ImportPKBudgetDataInput>()
            {
                Data = importData,
                Exception = string.IsNullOrEmpty(errorString) ? null : new Exception(errorString),
                RowErrors = rst.RowErrors,
                TemplateErrors = rst.TemplateErrors,
            };
            return resp;
        }




        /// <summary>
        /// 获取排课平台 培训认证中心/项目组
        /// </summary>
        /// <returns></returns>
        public async Task<PagedResultDto<GetPKBudgetDataOutput>> GetSchoolNameList()
        {
            RefAsync<int> totalCount = 0;
            GetPKBudgetDataOutput additem = new GetPKBudgetDataOutput();

            List<GetPKBudgetDataOutput> listDto = new List<GetPKBudgetDataOutput>();
            listDto.Add(new GetPKBudgetDataOutput()
            {
                SchoolName = "全部"
            });
            var page = _db.Queryable<PKBudgetData>().Select(x => new GetPKBudgetDataOutput
            {
                SchoolName = x.SchoolName,
            }).Distinct().ToList();
            listDto.AddRange(page);
            // 返回结果
            return new PagedResultDto<GetPKBudgetDataOutput>()
            {
                TotalCount = totalCount,
                Items = listDto
            };
        }

        /// <summary>
        /// 预算数据编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task EditAsync(ImportPKBudgetDataInput input)
        {
            var editdata = _db.Queryable<PKBudgetData>().Where(t => t.Id == input.Id).First();
            var user = _dbPlatform.Queryable<Users>().Where(p => p.WorkNumber == CurrentUser.UserName).Select(p => p).First();
            editdata.UpdateTime = DateTime.Now;
            editdata.UpdateUser = user.UserName;
            editdata.Year = input.Year;
            editdata.Month = input.Month;
            editdata.Budget = input.Budget == "" || input.Budget == null ? 0 : decimal.Parse(input.Budget);
            editdata.Estimate = input.Estimate == "" || input.Estimate == null ? 0 : decimal.Parse(input.Estimate);
            editdata.Practical = input.Practical == "" || input.Practical == null ? 0 : decimal.Parse(input.Practical);

            _db.Updateable(editdata).UpdateColumns(t => new { t.Year, t.Month, t.Budget, t.Estimate, t.Practical, t.UpdateTime, t.UpdateUser }).ExecuteCommand();
        }

        /// <summary>
        /// 预算数据删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync(Guid id)
        {
            var cnt = await _db.Deleteable<PKBudgetData>().Where(x => (x.Id == id)).ExecuteCommandAsync();
        }
        #endregion

        #region 校长提交
        /// <summary>
        /// 查询校长提交历史
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetPKSubmittedByPrincipalOutput>> GetPKSubmittedByPrincipalHistory(PKBudgetDataInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetHistoryQueryable(input);
            totalCount = listQueryable.Count();
            int index = (input.PageIndex - 1) * input.PageSize;
            int size = input.PageSize;
            if ((input.PageIndex * input.PageSize) > totalCount)
            {
                size = totalCount - index;
            }
            var listViewDto = listQueryable.ToList().GetRange(index, size);
            // var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);//查看
            });
            //返回结果
            return new PagedResultDto<GetPKSubmittedByPrincipalOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 获取开始链接
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetStartUrl()
        {
            return GetStartUrl("PKXZTJ").Result;//发起
        }

        /// <summary>
        /// 发起界面的地址
        /// </summary>
        /// <param name="instanceNumber"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<string> GetStartUrl(string btid)
        {
            var pUrl = string.Empty;
            var pcStartUrl = ConfigManager.PCStartUrl;
            var processes = await _dbProcess.Queryable<Processes>().Where(x => x.BTID == btid).ToListAsync();
            if (processes != null)
            {
                pUrl = string.Format(pcStartUrl, processes.FirstOrDefault().ProcessId);
            }
            return pUrl;
        }
        public async Task<PagedResultDto<GetPKSubmittedByPrincipalDetailOutput>> GetPKSubmittedByPrincipalDetailSearch(PKBudgetDataInput input)
        {
            RefAsync<int> totalCount = 0;
            var listQueryable = GetDetailQueryable(input);
            totalCount = listQueryable.Count();
            int index = (input.PageIndex - 1) * input.PageSize;
            int size = input.PageSize;
            if ((input.PageIndex * input.PageSize) > totalCount)
            {
                size = totalCount - index;
            }
            var listViewDto = listQueryable.ToList().GetRange(index, size);
            //  var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            var mapperList = ObjectMapper.Map<List<PKSubmittedByPrincipalDetail>, List<GetPKSubmittedByPrincipalDetailOutput>>(listViewDto);

            mapperList.ForEach(p =>
            {
                p.CourseTypeCode = showCourseTypeCode(p.CourseTypeCode);
                p.TeachWayCode = showTeachWayCode(p.TeachWayCode);
                p.CourseIsNew = showCourseIsNew(p.CourseIsNew);
                p.ClientCode = showClientCode(p.ClientCode);
            });
            //返回结果
            return new PagedResultDto<GetPKSubmittedByPrincipalDetailOutput>()
            {
                TotalCount = totalCount,
                Items = mapperList
            };
        }

        /// <summary>
        /// 获取Queryable(报表展现),校长提交历史
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<GetPKSubmittedByPrincipalOutput> GetHistoryQueryable(PKBudgetDataInput input)
        {
            var listQueryable = _db.Queryable<PKSubmittedByPrincipal>()
                    .WhereIF(!string.IsNullOrWhiteSpace(input.Year), (x) => x.Year == input.Year)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.Month), (x) => x.Month == input.Month)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.SchoolName) && input.SchoolName != "全部", (x) => x.SchoolName == input.SchoolName)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.Area) && input.Area != "全部", (x) => x.Area == input.Area)
                     .Select(x => new GetPKSubmittedByPrincipalOutput
                     {
                         Id = x.Id.ToString(),
                         CreateTime = x.CreateTime,
                         Year = x.Year,
                         Month = x.Month,
                         SchoolName = x.SchoolName,
                         EstimatedTotal = x.EstimatedTotal,
                         Status = x.Status,
                         SubmitNum = x.SubmitNum,
                         InstanceNumber = x.InstanceNumber,
                     }).MergeTable().OrderBy(x => x.CreateTime, OrderByType.Desc);

            return listQueryable;
        }

        private ISugarQueryable<PKSubmittedByPrincipalDetail> GetPKMonthPanoramaQueryable(PKMonthPanoramaInput input)
        {
            if (input.Year != 0 && input.Month != 0)
            {
                var listQueryable = _db.Queryable<PKSubmittedByPrincipal, PKSubmittedByPrincipalDetail, KeyValues>(
                    (a, p, k) => new JoinQueryInfos(JoinType.Left, a.InstanceNumber == p.InstanceNumber, JoinType.Left, p.SchoolName == k.Name))
                        .WhereIF(!string.IsNullOrWhiteSpace(input.SchoolName) && input.SchoolName != "全部", (a, p, k) => p.SchoolName == input.SchoolName)
                        .WhereIF(!string.IsNullOrWhiteSpace(input.SchoolArea) && input.SchoolArea != "全部", (a, p, k) => k.ParentCode == input.SchoolArea)
                        .WhereIF(input.Year != 0, (a, p, k) => DateTime.Parse(p.TrainEndDate).Year == input.Year)
                        .WhereIF(input.Month != 0, (a, p, k) => DateTime.Parse(p.TrainEndDate).Month >= input.Month && DateTime.Parse(p.TrainStartDate).Month <= input.Month)
                        .Select((a, p, k) => new PKSubmittedByPrincipalDetail
                        {
                            CourseName = p.CourseName,
                            //SortNo = p.SortNo,
                            SortNo = k.Sort.Value,
                            TrainStartDate = p.TrainStartDate,
                            TrainEndDate = p.TrainEndDate,
                            EstimatedStudentCount = p.EstimatedStudentCount,
                            EstimatedRevenue = p.EstimatedRevenue,
                            CreateTime = p.CreateTime,
                            SchoolName = p.SchoolName,
                            MaxfitStudentCount = p.MaxfitStudentCount,
                            Area = p.Area,
                            ClassBase = p.ClassBase,
                        }).MergeTable().OrderBy(k => k.SortNo).OrderBy(a => a.Area).OrderBy(a => a.SchoolName).OrderBy(a => a.SortNo);

                return listQueryable;
            }
            return null;
        }

        /// <summary>
        /// 财务报表取明细数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<PKSubmittedByPrincipalDetail> GetDetailQueryable(PKBudgetDataInput input)
        {
            var listQueryable = _db.Queryable<PKSubmittedByPrincipal, PKSubmittedByPrincipalDetail>((b, p) =>
                  new JoinQueryInfos(JoinType.Inner, b.InstanceNumber == p.InstanceNumber))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.Year), (b, p) => p.Year == input.Year)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.Month), (b, p) => p.Month == input.Month)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.SchoolName) && input.SchoolName != "全部", (b, p) => p.SchoolName == input.SchoolName)
                    .WhereIF(!string.IsNullOrWhiteSpace(input.Area) && input.Area != "全部", (b, p) => p.Area == input.Area)
                     .Select((b, p) => new PKSubmittedByPrincipalDetail
                     {
                         Id = p.Id,
                         // InstanceNumber = p.InstanceNumber,
                         Area = p.Area,
                         SchoolName = p.SchoolName,
                         SortNo = p.SortNo,
                         Year = p.Year,
                         Month = p.Month,
                         CourseCode = p.CourseCode,
                         CourseName = p.CourseName,
                         Amount = p.Amount,
                         CourseNature = p.CourseNature,
                         ChargeTypeCode = p.ChargeTypeCode,
                         CourseTypeCode = p.CourseTypeCode,
                         TeachWayCode = p.TeachWayCode,
                         TrainingObjects = p.TrainingObjects,
                         ChargeWay = p.ChargeWay,
                         CourseIsNew = p.CourseIsNew,
                         StandardTeacherCount = p.StandardTeacherCount,
                         StandardStudentCount = p.StandardStudentCount,
                         ClientCode = p.ClientCode,
                         BU = p.BU,
                         TrainStartDate = p.TrainStartDate,
                         TrainEndDate = p.TrainEndDate,
                         TrainDays = p.TrainDays,
                         TeachCity = p.TeachCity,
                         EstimatedStudentCount = p.EstimatedStudentCount,
                         EstimatedNumberClasses = p.EstimatedNumberClasses,
                         ChargeDif = p.ChargeDif,
                         EstimatedRevenue = p.EstimatedRevenue,
                         CreateTime = p.CreateTime,
                         TheoryTeacher = p.TheoryTeacher,
                         PracticeTeacher = p.PracticeTeacher,
                         ClassBase = p.ClassBase,
                     }).MergeTable().OrderBy(p => p.CreateTime, OrderByType.Desc).OrderBy(p => p.SortNo);

            return listQueryable;
        }


        /// <summary>
        ///  校长提交明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetPKSubmittedByPrincipalDetailOutput>> GetPKSubmittedByPrincipalDetail(PKBudgetDataInput input)
        {
            var listQueryable = GetDetailQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();

            var mapperList = ObjectMapper.Map<List<PKSubmittedByPrincipalDetail>, List<GetPKSubmittedByPrincipalDetailOutput>>(listViewDto);

            mapperList.ForEach(p =>
            {
                p.CourseTypeCode = showCourseTypeCode(p.CourseTypeCode);
                p.TeachWayCode = showTeachWayCode(p.TeachWayCode);
                p.CourseIsNew = showCourseIsNew(p.CourseIsNew);
                p.ClientCode = showClientCode(p.ClientCode);
            });
            return mapperList;
        }

        public string showCourseTypeCode(string courseTypeCode)
        {
            //课程类型
            switch (courseTypeCode)
            {
                case "X":
                    return "项目类(X)";
                case "T":
                    return "通识类(T)";
                case "M":
                    return "管理类(M)";
                case "Z":
                    return "专业类(Z)";
                case "G":
                    return "工具类(G)";
                case "R":
                    return "认证类(R)";
                case "C":
                    return "资讯类(C)";
                case "Q":
                    return "其他(Q)";
                default: return courseTypeCode;
            }
        }
        public string showTeachWayCode(string teachWayCode)
        {
            //授课方式
            switch (teachWayCode)
            {
                case "1":
                    return "线上(1)";
                case "2":
                    return "线下(2)";
                case "3":
                    return "线上+线下(3)";
                case "4":
                    return "视频微课(4)";
                default: return teachWayCode;
            }
        }
        public string showCourseIsNew(string courseIsNew)
        {
            //新/旧课程
            switch (courseIsNew)
            {
                case "true":
                    return "是";
                case "false":
                    return "否";
                default: return "";
            }
        }
        public string showClientCode(string courseIsNew)
        {
            //事业部
            switch (courseIsNew)
            {
                case "01":
                    return "TUC(01)";
                case "02":
                    return "TUB(02)";
                case "03":
                    return "刷新(03)";
                case "04":
                    return "厨卫(04)";
                case "05":
                    return "爱客(05)";
                case "07":
                    return "臻辅材(07)";
                case "08":
                    return "生产供应链(08)";
                case "09":
                    return "其他(09)";
                default: return "";
            }
        }
        /// <summary>
        /// 全景图规划月取值
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetPKMonthPanoramaOutPut>> GetMonthPanorama(PKMonthPanoramaInput input)
        {
            var listQueryable = GetPKMonthPanoramaQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            // 获取当前月份的第一天
            DateTime firstDayOfMonth = new DateTime(input.Year, input.Month, 1);
            // 获取当前月份的最后一天
            DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);

            //判断培训开始到结束有多少天，然后按照日期填充进日期字段中
            //预估人次、预付收入合计取值按照课程最后一天去合计，存在跨月情况，统计到下个月去合计
            var result = new List<GetPKMonthPanoramaOutPut>();
            //预计人次
            decimal studentCount = 0;
            decimal revenue = 0;
            //只显示在月内的数据，跨月就算到下个月，开始时间在这个月的也算进去
            studentCount = listViewDto.Where(q=> DateTime.Parse(q.TrainEndDate).Month== input.Month).Sum(p => p.EstimatedStudentCount);
            revenue = listViewDto.Where(q => DateTime.Parse(q.TrainEndDate).Month == input.Month).Sum(p => p.EstimatedRevenue);
            if (listViewDto.Count() > 0)
            {
                List<GetPKMonthPanoramaOutPut.detailList> myList = new List<GetPKMonthPanoramaOutPut.detailList>();
                // 添加元素到myList
                for (int i = 1; i < 31; i++)
                {
                    var obj = new GetPKMonthPanoramaOutPut.detailList();
                    obj.date1 = "date" + i;
                    myList.Add(obj);
                }

                for (int i = 0; i < listViewDto.Count(); i++)
                {
                    var newlist = new GetPKMonthPanoramaOutPut();
                    //返回结果
                    newlist.tjTitle = "计划排班";
                    newlist.tjNum = $"{listViewDto.Count()} ";
                    DateTime start = Convert.ToDateTime(listViewDto[i].TrainStartDate);
                    DateTime end = Convert.ToDateTime(listViewDto[i].TrainEndDate);

                    string area = listViewDto[i].Area;
                    string schoolName = listViewDto[i].SchoolName;
                    if (schoolName.Contains("学校"))
                    {
                        schoolName = schoolName.Replace("学校", string.Empty);
                    }
                    string courseName = 
                        (string.IsNullOrEmpty(listViewDto[i].ClassBase) ? $"【{schoolName}】" : $"【{schoolName},{listViewDto[i].ClassBase}】") +
                        $"{listViewDto[i].CourseName}" +
                        $"({Math.Round(listViewDto[i].EstimatedStudentCount, 0)}/" +
                        $"{Math.Round(listViewDto[i].MaxfitStudentCount, 0)})!$$!预估!$$!P";
                    bool idadd = true;
                    if (i > 0)
                    {
                        int t = i - 1;
                        DateTime prstart = Convert.ToDateTime(listViewDto[t].TrainStartDate);
                        DateTime prend = Convert.ToDateTime(listViewDto[t].TrainEndDate);
                        string prcourseName = listViewDto[t].CourseName;
                        string prarea = listViewDto[t].Area;
                        if (!IsOverlap(prstart, prend, start, end) && area == prarea)
                        {
                            //时间不重叠,培训认证中心/项目组相同，拼成一条
                            var daily = new GetPKMonthPanoramaOutPut.detailList();
                            bool isdaily = false;
                            for (var date = Convert.ToDateTime(start);date <= Convert.ToDateTime(end); date = date.AddDays(1))
                            {
                                DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                                if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                                {
                                    string dateV = "date" + dateStr.Day;
                                    // 通过属性名称为指定列赋值
                                    PropertyInfo property = typeof(GetPKMonthPanoramaOutPut.detailList).GetProperty(dateV);
                                    if (property != null && property.CanWrite)
                                    {
                                        foreach (var item in myList)
                                        {
                                            if (property.GetValue(item) == null && !isdaily)
                                            {
                                                property.SetValue(item, courseName, null);
                                                newlist.dailyList = item;
                                            }
                                            else
                                            {
                                                isdaily = true;
                                                property.SetValue(daily, courseName, null);
                                            }
                                        }
                                    }
                                }
                            }
                            if (isdaily)
                            {
                                newlist.dailyList = daily;
                                myList.Clear();
                                myList.Add(daily);
                                result.Add(newlist);
                            }
                            idadd = false;
                        }
                        else
                        {
                            idadd = true;
                        }
                    }
                    if (idadd)
                    {
                        var daily = new GetPKMonthPanoramaOutPut.detailList();
                        for (var date = Convert.ToDateTime(start); date <= Convert.ToDateTime(end); date = date.AddDays(1))
                        {
                            DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                            if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                            {
                                string dateV = "date" + dateStr.Day;
                                if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                                {
                                    //遍历类中属性
                                    foreach (System.Reflection.PropertyInfo info in daily.GetType().GetProperties())
                                    {
                                        var value = daily.GetType().GetProperty(info.Name).Name;
                                        if (value == dateV)
                                        {
                                            info.SetValue(daily, courseName, null);
                                        }
                                    }
                                }
                            }
                        }
                        newlist.dailyList = daily;
                        myList.Clear();
                        myList.Add(daily);
                        result.Add(newlist);
                    }
                }
            }

            var newResult2 = new GetPKMonthPanoramaOutPut();
            newResult2.tjTitle = "预估人次";
            newResult2.tjNum = $"{studentCount}  ";
            newResult2.dailyList = getDateSumList(listViewDto, 1, input);

            var newResult3 = new GetPKMonthPanoramaOutPut();
            newResult3.tjTitle = "预估收入";
            newResult3.tjNum = $"{Math.Round(revenue, 0)}   ";
            newResult3.dailyList = getDateSumList(listViewDto, 2, input);
            result.Add(newResult2);
            result.Add(newResult3);
            return result;
        }


        public GetPKMonthPanoramaOutPut.detailList getDateSumList(List<PKSubmittedByPrincipalDetail> list, int type, PKMonthPanoramaInput input)
        {
            var result = new GetPKMonthPanoramaOutPut.detailList();
            //预估人次、预付收入合计取值按照课程最后一天去合计，存在跨月情况，统计到下个月去合计
            //如果存在跨周末、跨月的可能性，以最后一天为准计算
            var dailylist = new List<GetPKMonthPanoramaOutPut.detailList>();
            list = list.OrderBy(p => p.TrainEndDate).ToList();
            //如果上一条和下一条的周末相同，就把它们的值累计相加，赋给这周的每一天
            DateTime lastDayOfWeekNew = DateTime.Now;
            decimal studentCount = 0;
            decimal estimatedRevenue = 0;
            for (int i = 0; i < list.Count; i++)
            {
                //星期一为第一天
                DateTime currentDate = DateTime.Parse(list[i].TrainEndDate);
                //如果不是在查询的这个月中，不统计
                if (currentDate.Year == input.Year && currentDate.Month == input.Month)
                {
                    int weeknow = Convert.ToInt32(currentDate.DayOfWeek);

                    //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。
                    weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
                    int daydiff = (-1) * weeknow;
                    //本周第一天
                    DateTime firstDayOfWeek = currentDate.AddDays(daydiff);

                    //星期天为最后一天
                    int weeknow2 = Convert.ToInt32(currentDate.DayOfWeek);
                    weeknow2 = (weeknow2 == 0 ? 7 : weeknow2);
                    int daydiff2 = (7 - weeknow2);
                    //本周最后一天
                    DateTime lastDayOfWeek = currentDate.AddDays(daydiff2);
                    DateTime lastDayOfWeek2 = currentDate.AddDays(daydiff2);
                    // 获取当前月份的第一天
                    DateTime firstDayOfMonth = new DateTime(input.Year, input.Month, 1);
                    // 获取当前月份的最后一天
                    DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

                    var day = currentDate.DayOfWeek;
                    if (day != DayOfWeek.Sunday && day != DayOfWeek.Saturday)
                    {
                        lastDayOfWeek = currentDate.AddDays(5 - weeknow2);//默认按五天为一个阶段
                    }
                    if (day == DayOfWeek.Sunday)
                    {
                        //判断是否为周末
                        lastDayOfWeek = currentDate;
                    }
                    if (day == DayOfWeek.Saturday)
                    {
                        //判断是否为周六
                        lastDayOfWeek = currentDate.AddDays(6 - weeknow2);
                    }
                    if (currentDate == lastDayOfMonth)
                    {
                        //是否为这个月的最后一天
                        lastDayOfWeek = lastDayOfMonth;
                    }
                    if (lastDayOfWeek.Month != firstDayOfWeek.Month && lastDayOfWeek.Day < firstDayOfWeek.Day)
                    {
                        //跨月又跨周的情况是取这个月的最后一天
                        TimeSpan ts = lastDayOfMonth - lastDayOfWeek;
                        double dbl = ts.TotalDays;
                        int intDow = Convert.ToInt32(lastDayOfMonth.DayOfWeek);

                        if (intDow == 0) intDow = 7;

                        if (dbl >= 7 || dbl >= intDow)
                        {
                        }
                        else
                        {
                            lastDayOfWeek = lastDayOfMonth;
                        }
                    }
                    if (firstDayOfWeek.Month != lastDayOfWeek.Month)
                    {
                        //一周中有不同月份的时间，取相同月份
                        firstDayOfWeek = lastDayOfWeek.AddDays(-lastDayOfWeek.Day + 1);
                    }
                    //如果上一条和下一条的周末相同，就把它们的值累计相加，赋给这周的每一天
                    if (i > 0)
                    {
                        if (lastDayOfWeekNew == lastDayOfWeek2)
                        {
                            if (type == 1)
                            {
                                studentCount += list[i].EstimatedStudentCount;
                            }
                            else
                            {
                                estimatedRevenue += list[i].EstimatedRevenue;
                            }
                            if (dailylist.Count > 0)
                            {
                                dailylist.RemoveAt(dailylist.Count - 1);
                            }
                        }
                        else
                        {
                            if (type == 1)
                            {
                                studentCount = list[i].EstimatedStudentCount;
                            }
                            else
                            {
                                estimatedRevenue = list[i].EstimatedRevenue;
                            }
                        }
                        lastDayOfWeekNew = lastDayOfWeek2;
                    }
                    else
                    {
                        if (type == 1)
                        {
                            studentCount = list[i].EstimatedStudentCount;
                        }
                        else
                        {
                            estimatedRevenue = list[i].EstimatedRevenue;
                        }
                        lastDayOfWeekNew = lastDayOfWeek2;
                    }

                    var daily = new GetPKMonthPanoramaOutPut.detailList();
                    if (firstDayOfWeek.Day < lastDayOfWeek.Day)
                    {
                        //同一个月
                        for (var date = firstDayOfWeek; date <= lastDayOfWeek; date = date.AddDays(1))
                        {
                            DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                            string dateV = "date" + dateStr.Day;
                            decimal num = 0;
                            //遍历类中属性
                            foreach (System.Reflection.PropertyInfo info in daily.GetType().GetProperties())
                            {
                                //通过属性名称获取属性的值
                                var value = daily.GetType().GetProperty(info.Name).Name;
                                if (value == dateV)
                                {
                                    if (type == 1)
                                    {
                                        num = studentCount;
                                    }
                                    else
                                    {
                                        num = estimatedRevenue;
                                    }
                                    // 获取属性信息
                                    //PropertyInfo propInfo = typeof(GetPKMonthPanoramaOutPut.detailList).GetProperty(dateV);
                                    //if (propInfo != null && propInfo.CanRead && propInfo.CanWrite)
                                    //{
                                    //    // 设置属性值
                                    //    propInfo.SetValue(daily, num.ToString());
                                    //}
                                    info.SetValue(daily, num.ToString(), null);
                                }
                            }
                        }
                        dailylist.Add(daily);
                    }
                    else
                    {
                        //不同月
                        for (var date = lastDayOfWeek; date <= lastDayOfWeek; date = date.AddDays(1))
                        {
                            DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                            string dateV = "date" + dateStr.Day;
                            decimal num = 0;

                            //遍历类中属性
                            foreach (System.Reflection.PropertyInfo info in daily.GetType().GetProperties())
                            {
                                //通过属性名称获取属性的值
                                var value = daily.GetType().GetProperty(info.Name).Name;
                                if (value == dateV)
                                {
                                    if (type == 1)
                                    {
                                        num = studentCount;
                                    }
                                    else
                                    {
                                        num = estimatedRevenue;
                                    }
                                    info.SetValue(daily, num.ToString(), null);
                                }
                            }
                        }
                        dailylist.Add(daily);
                    }
                }
            }

            //统计每天的人数和预估收入相加
            decimal date1 = 0, date2 = 0, date3 = 0, date4 = 0, date5 = 0, date6 = 0, date7 = 0, date8 = 0, date9 = 0, date10 = 0, date11 = 0, date12 = 0
                , date13 = 0, date14 = 0, date15 = 0, date16 = 0, date17 = 0, date18 = 0, date19 = 0, date20 = 0, date21 = 0, date22 = 0, date23 = 0
                , date24 = 0, date25 = 0, date26 = 0, date27 = 0, date28 = 0, date29 = 0, date30 = 0, date31 = 0;
            for (int i = 0; i < dailylist.Count; i++)
            {
                if (dailylist[i].date1 != null)
                {
                    date1 += decimal.Parse(dailylist[i].date1);
                    result.date1 = date1.ToString();
                }
                if (dailylist[i].date2 != null)
                {
                    date2 += decimal.Parse(dailylist[i].date2);
                    result.date2 = date2.ToString();
                }
                if (dailylist[i].date3 != null)
                {
                    date3 += decimal.Parse(dailylist[i].date3);
                    result.date3 = date3.ToString();
                }
                if (dailylist[i].date4 != null)
                {
                    date4 += decimal.Parse(dailylist[i].date4);
                    result.date4 = date4.ToString();
                }
                if (dailylist[i].date5 != null)
                {
                    date5 += decimal.Parse(dailylist[i].date5);
                    result.date5 = date5.ToString();
                }
                if (dailylist[i].date6 != null)
                {
                    date6 += decimal.Parse(dailylist[i].date6);
                    result.date6 = date6.ToString();
                }
                if (dailylist[i].date7 != null)
                {
                    date7 += decimal.Parse(dailylist[i].date7);
                    result.date7 = date7.ToString();
                }
                if (dailylist[i].date8 != null)
                {
                    date8 += decimal.Parse(dailylist[i].date8);
                    result.date8 = date8.ToString();
                }
                if (dailylist[i].date9 != null)
                {
                    date9 += decimal.Parse(dailylist[i].date9);
                    result.date9 = date9.ToString();
                }
                if (dailylist[i].date10 != null)
                {
                    date10 += decimal.Parse(dailylist[i].date10);
                    result.date10 = date10.ToString();
                }
                if (dailylist[i].date11 != null)
                {
                    date11 += decimal.Parse(dailylist[i].date11);
                    result.date11 = date11.ToString();
                }
                if (dailylist[i].date12 != null)
                {
                    date12 += decimal.Parse(dailylist[i].date12);
                    result.date12 = date12.ToString();
                }
                if (dailylist[i].date13 != null)
                {
                    date13 += decimal.Parse(dailylist[i].date13);
                    result.date13 = date13.ToString();
                }
                if (dailylist[i].date14 != null)
                {
                    date14 += decimal.Parse(dailylist[i].date14);
                    result.date14 = date14.ToString();
                }
                if (dailylist[i].date15 != null)
                {
                    date15 += decimal.Parse(dailylist[i].date15);
                    result.date15 = date15.ToString();
                }
                if (dailylist[i].date16 != null)
                {
                    date16 += decimal.Parse(dailylist[i].date16);
                    result.date16 = date16.ToString();
                }
                if (dailylist[i].date17 != null)
                {
                    date17 += decimal.Parse(dailylist[i].date17);
                    result.date17 = date17.ToString();
                }
                if (dailylist[i].date18 != null)
                {
                    date18 += decimal.Parse(dailylist[i].date18);
                    result.date18 = date18.ToString();
                }
                if (dailylist[i].date19 != null)
                {
                    date19 += decimal.Parse(dailylist[i].date19);
                    result.date19 = date19.ToString();
                }
                if (dailylist[i].date20 != null)
                {
                    date20 += decimal.Parse(dailylist[i].date20);
                    result.date20 = date20.ToString();
                }
                if (dailylist[i].date21 != null)
                {
                    date21 += decimal.Parse(dailylist[i].date21);
                    result.date21 = date21.ToString();
                }
                if (dailylist[i].date22 != null)
                {
                    date22 += decimal.Parse(dailylist[i].date22);
                    result.date22 = date22.ToString();
                }
                if (dailylist[i].date23 != null)
                {
                    date23 += decimal.Parse(dailylist[i].date23);
                    result.date23 = date23.ToString();
                }
                if (dailylist[i].date24 != null)
                {
                    date24 += decimal.Parse(dailylist[i].date24);
                    result.date24 = date24.ToString();
                }
                if (dailylist[i].date25 != null)
                {
                    date25 += decimal.Parse(dailylist[i].date25);
                    result.date25 = date25.ToString();
                }
                if (dailylist[i].date26 != null)
                {
                    date26 += decimal.Parse(dailylist[i].date26);
                    result.date26 = date26.ToString();
                }
                if (dailylist[i].date27 != null)
                {
                    date27 += decimal.Parse(dailylist[i].date27);
                    result.date27 = date27.ToString();
                }
                if (dailylist[i].date28 != null)
                {
                    date28 += decimal.Parse(dailylist[i].date28);
                    result.date28 = date28.ToString();
                }
                if (dailylist[i].date29 != null)
                {
                    date29 += decimal.Parse(dailylist[i].date29);
                    result.date29 = date29.ToString();
                }
                if (dailylist[i].date30 != null)
                {
                    date30 += decimal.Parse(dailylist[i].date30);
                    result.date30 = date30.ToString();
                }
                if (dailylist[i].date31 != null)
                {
                    date31 += decimal.Parse(dailylist[i].date31);
                    result.date31 = date31.ToString();
                }
            }

            #region 取整
            result.date1 = string.IsNullOrEmpty(result.date1) ? result.date1 : Math.Round(decimal.Parse(result.date1), 0).ToString();
            result.date2 = string.IsNullOrEmpty(result.date2) ? result.date2 : Math.Round(decimal.Parse(result.date2), 0).ToString();
            result.date3 = string.IsNullOrEmpty(result.date3) ? result.date3 : Math.Round(decimal.Parse(result.date3), 0).ToString();
            result.date4 = string.IsNullOrEmpty(result.date4) ? result.date4 : Math.Round(decimal.Parse(result.date4), 0).ToString();
            result.date5 = string.IsNullOrEmpty(result.date5) ? result.date5 : Math.Round(decimal.Parse(result.date5), 0).ToString();
            result.date6 = string.IsNullOrEmpty(result.date6) ? result.date6 : Math.Round(decimal.Parse(result.date6), 0).ToString();
            result.date7 = string.IsNullOrEmpty(result.date7) ? result.date7 : Math.Round(decimal.Parse(result.date7), 0).ToString();
            result.date8 = string.IsNullOrEmpty(result.date8) ? result.date8 : Math.Round(decimal.Parse(result.date8), 0).ToString();
            result.date9 = string.IsNullOrEmpty(result.date9) ? result.date9 : Math.Round(decimal.Parse(result.date9), 0).ToString();
            result.date10 = string.IsNullOrEmpty(result.date10) ? result.date10 : Math.Round(decimal.Parse(result.date10), 0).ToString();
            result.date11 = string.IsNullOrEmpty(result.date11) ? result.date11 : Math.Round(decimal.Parse(result.date11), 0).ToString();
            result.date12 = string.IsNullOrEmpty(result.date12) ? result.date12 : Math.Round(decimal.Parse(result.date12), 0).ToString();
            result.date13 = string.IsNullOrEmpty(result.date13) ? result.date13 : Math.Round(decimal.Parse(result.date13), 0).ToString();
            result.date14 = string.IsNullOrEmpty(result.date14) ? result.date14 : Math.Round(decimal.Parse(result.date14), 0).ToString();
            result.date15 = string.IsNullOrEmpty(result.date15) ? result.date15 : Math.Round(decimal.Parse(result.date15), 0).ToString();
            result.date16 = string.IsNullOrEmpty(result.date16) ? result.date16 : Math.Round(decimal.Parse(result.date16), 0).ToString();
            result.date17 = string.IsNullOrEmpty(result.date17) ? result.date17 : Math.Round(decimal.Parse(result.date17), 0).ToString();
            result.date18 = string.IsNullOrEmpty(result.date18) ? result.date18 : Math.Round(decimal.Parse(result.date18), 0).ToString();
            result.date19 = string.IsNullOrEmpty(result.date19) ? result.date19 : Math.Round(decimal.Parse(result.date19), 0).ToString();
            result.date20 = string.IsNullOrEmpty(result.date20) ? result.date20 : Math.Round(decimal.Parse(result.date20), 0).ToString();
            result.date21 = string.IsNullOrEmpty(result.date21) ? result.date21 : Math.Round(decimal.Parse(result.date21), 0).ToString();
            result.date22 = string.IsNullOrEmpty(result.date22) ? result.date22 : Math.Round(decimal.Parse(result.date22), 0).ToString();
            result.date23 = string.IsNullOrEmpty(result.date23) ? result.date23 : Math.Round(decimal.Parse(result.date23), 0).ToString();
            result.date24 = string.IsNullOrEmpty(result.date24) ? result.date24 : Math.Round(decimal.Parse(result.date24), 0).ToString();
            result.date25 = string.IsNullOrEmpty(result.date25) ? result.date25 : Math.Round(decimal.Parse(result.date25), 0).ToString();
            result.date26 = string.IsNullOrEmpty(result.date26) ? result.date26 : Math.Round(decimal.Parse(result.date26), 0).ToString();
            result.date27 = string.IsNullOrEmpty(result.date27) ? result.date27 : Math.Round(decimal.Parse(result.date27), 0).ToString();
            result.date28 = string.IsNullOrEmpty(result.date28) ? result.date28 : Math.Round(decimal.Parse(result.date28), 0).ToString();
            result.date29 = string.IsNullOrEmpty(result.date29) ? result.date29 : Math.Round(decimal.Parse(result.date29), 0).ToString();
            result.date30 = string.IsNullOrEmpty(result.date30) ? result.date30 : Math.Round(decimal.Parse(result.date30), 0).ToString();
            result.date31 = string.IsNullOrEmpty(result.date31) ? result.date31 : Math.Round(decimal.Parse(result.date31), 0).ToString();
            #endregion
            return result;
        }

        /// <summary>
        /// 判断时间区间是否重叠
        /// </summary>
        /// <param name="StartTime1"></param>
        /// <param name="EndTime1"></param>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public bool IsOverlap(DateTime a, DateTime b, DateTime x, DateTime y)
        {
            //时间无重叠                 
            if ((b < x) || (y < a))
            {
                return false;
            }
            //2.b)否则有重叠，去掉原先的a；
            //重叠
            if ((a < x) && (x <= b))
            {
                return true;
            }
            if ((a <= y) && (y < b))
            {
                return true;
            }
            if ((a < y) && (b == x))
            {
                return true;
            }
            if (a == x || b == y)
            {
                return true;
            }
            if (a >= x && b <= y)
            {
                return true;
            }
            return false;
        }

        #endregion
        #region 校长提交实际
        public async Task<PagedResultDto<GetPKSubmittedByPrincipalRealOutput>> GetPKSubmittedByPrincipalRealHistory(PKBudgetDataInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetRealHistoryQueryable(input);
            totalCount = listQueryable.Count();
            int index = (input.PageIndex - 1) * input.PageSize;
            int size = input.PageSize;
            if ((input.PageIndex * input.PageSize) > totalCount)
            {
                size = totalCount - index;
            }
            var listViewDto = listQueryable.ToList().GetRange(index, size);
            // var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);//查看
            });
            //返回结果
            return new PagedResultDto<GetPKSubmittedByPrincipalRealOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }
        public async Task<string> GetRealStartUrl()
        {
            return GetStartUrl("PKXZSJ").Result;//发起
        }
        private ISugarQueryable<GetPKSubmittedByPrincipalRealOutput> GetRealHistoryQueryable(PKBudgetDataInput input)
        {
            var listQueryable = _db.Queryable<PKSubmittedByPrincipalReal>()
                    .WhereIF(!string.IsNullOrWhiteSpace(input.Year), (x) => x.Year == input.Year)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.Month), (x) => x.Month == input.Month)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.SchoolName) && input.SchoolName != "全部", (x) => x.SchoolName == input.SchoolName)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.Area) && input.Area != "全部", (x) => x.Area == input.Area)
                     .Select(x => new GetPKSubmittedByPrincipalRealOutput
                     {
                         Id = x.Id.ToString(),
                         CreateTime = x.CreateTime,
                         Year = x.Year,
                         Month = x.Month,
                         SchoolName = x.SchoolName,
                         EstimatedTotal = x.EstimatedTotal,
                         Status = x.Status,
                         SubmitNum = x.SubmitNum,
                         InstanceNumber = x.InstanceNumber,
                     }).MergeTable().OrderBy(x => x.CreateTime, OrderByType.Desc);

            return listQueryable;
        }

        /// <summary>
        /// 全景图实际月取值
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetPKMonthPanoramaOutPut>> GetMonthReal(PKMonthPanoramaInput input)
        {
            var listQueryable = GetPKMonthRealQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();

            

            // 获取当前月份的第一天
            DateTime firstDayOfMonth = new DateTime(input.Year, input.Month, 1);
            // 获取当前月份的最后一天
            DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);

            //判断培训开始到结束有多少天，然后按照日期填充进日期字段中
            //预估人次、预付收入合计取值按照课程最后一天去合计，存在跨月情况，统计到下个月去合计
            var result = new List<GetPKMonthPanoramaOutPut>();
            //预计人次
            decimal studentCount = 0;
            decimal revenue = 0;
            //只显示在月内的数据，跨月就算到下个月，开始时间在这个月的也算进去
            studentCount = listViewDto.Where(q => DateTime.Parse(q.TrainEndDate).Month == input.Month).Sum(p => p.EstimatedStudentCount);
            revenue = listViewDto.Where(q => DateTime.Parse(q.TrainEndDate).Month == input.Month).Sum(p => p.EstimatedRevenue);
            if (listViewDto.Count() > 0)
            {
                List<GetPKMonthPanoramaOutPut.detailList> myList = new List<GetPKMonthPanoramaOutPut.detailList>();
                // 添加元素到myList
                for (int i = 1; i < 31; i++)
                {
                    var obj = new GetPKMonthPanoramaOutPut.detailList();
                    obj.date1 = "date" + i;
                    myList.Add(obj);
                }

                for (int i = 0; i < listViewDto.Count(); i++)
                {
                    var newlist = new GetPKMonthPanoramaOutPut();
                    //返回结果
                    newlist.tjTitle = "实际排班";
                    newlist.tjNum = $"{listViewDto.Count() }";
                    DateTime start = Convert.ToDateTime(listViewDto[i].TrainStartDate);
                    DateTime end = Convert.ToDateTime(listViewDto[i].TrainEndDate);

                    string area = listViewDto[i].Area;
                    string schoolName = listViewDto[i].SchoolName;

                    
                    if (schoolName.Contains("学校"))
                    {
                        schoolName = schoolName.Replace("学校", string.Empty);
                    }
                    //string courseName = "【" + schoolName + "】" + listViewDto[i].CourseName+"("+ Math.Round(listViewDto[i].EstimatedStudentCount,0) + "/" + Math.Round(listViewDto[i].MaxfitStudentCount, 0) + ")"
                    //                  + "!$$!"+ listViewDto[i].ChangeTypeCode
                    //                  + "!$$!R";
                    string courseName =
                        (string.IsNullOrEmpty(listViewDto[i].ClassBase) ? $"【{schoolName}】" : $"【{schoolName},{listViewDto[i].ClassBase}】") +
                        $"{listViewDto[i].CourseName}" +
                        $"({Math.Round(listViewDto[i].EstimatedStudentCount, 0)}/" +
                        $"{Math.Round(listViewDto[i].MaxfitStudentCount, 0)})!$$!{listViewDto[i].ChangeTypeCode}!$$!R";
                    bool idadd = true;
                    if (i > 0)
                    {
                        int t = i - 1;
                        DateTime prstart = Convert.ToDateTime(listViewDto[t].TrainStartDate);
                        DateTime prend = Convert.ToDateTime(listViewDto[t].TrainEndDate);
                        string prcourseName = listViewDto[t].CourseName;
                        string prarea = listViewDto[t].Area;
                        if (!IsOverlap(prstart, prend, start, end) && area == prarea)
                        {
                            //时间不重叠,培训认证中心/项目组相同，拼成一条
                            var daily = new GetPKMonthPanoramaOutPut.detailList();
                            bool isdaily = false;
                            for (var date = Convert.ToDateTime(start); date <= Convert.ToDateTime(end); date = date.AddDays(1))
                            {
                                DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                                if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                                {
                                    string dateV = "date" + dateStr.Day;
                                    // 通过属性名称为指定列赋值
                                    PropertyInfo property = typeof(GetPKMonthPanoramaOutPut.detailList).GetProperty(dateV);
                                    if (property != null && property.CanWrite)
                                    {
                                        foreach (var item in myList)
                                        {
                                            if (property.GetValue(item) == null && !isdaily)
                                            {
                                                property.SetValue(item, courseName, null);
                                                newlist.dailyList = item;
                                            }
                                            else
                                            {
                                                isdaily = true;
                                                property.SetValue(daily, courseName, null);
                                            }
                                        }
                                    }
                                }
                            }
                            if (isdaily)
                            {
                                newlist.dailyList = daily;
                                myList.Clear();
                                myList.Add(daily);
                                result.Add(newlist);
                            }
                            idadd = false;
                        }
                        else
                        {
                            idadd = true;
                        }
                    }
                    if (idadd)
                    {
                        var daily = new GetPKMonthPanoramaOutPut.detailList();
                        for (var date = Convert.ToDateTime(start); date <= Convert.ToDateTime(end); date = date.AddDays(1))
                        {
                            DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                            if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                            {
                                string dateV = "date" + dateStr.Day;
                                if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                                {
                                    //遍历类中属性
                                    foreach (System.Reflection.PropertyInfo info in daily.GetType().GetProperties())
                                    {
                                        var value = daily.GetType().GetProperty(info.Name).Name;
                                        if (value == dateV)
                                        {
                                            info.SetValue(daily, courseName, null);
                                        }
                                    }
                                }
                            }
                        }
                        newlist.dailyList = daily;
                        myList.Clear();
                        myList.Add(daily);
                        result.Add(newlist);
                    }
                }
            }

            var newResult2 = new GetPKMonthPanoramaOutPut();
            newResult2.tjTitle = "实际人次";
            newResult2.tjNum = $"{studentCount}  ";
            newResult2.dailyList = getDateSumListReal(listViewDto, 1, input);

            var newResult3 = new GetPKMonthPanoramaOutPut();
            newResult3.tjTitle = "应收收入";
            newResult3.tjNum = $"{Math.Round(revenue, 0)}   ";
            newResult3.dailyList = getDateSumListReal(listViewDto, 2, input);
            result.Add(newResult2);
            result.Add(newResult3);
            return result;
        }

        public async Task<List<GetPKMonthPanoramaOutPut>> GetMonthRealandEstimate(PKMonthPanoramaInput input)
        {
            #region 基础数据
            //实际数据
            var listQueryable_real = GetPKMonthRealQueryable(input);
            var listViewDto_real = await listQueryable_real.ToListAsync();

            //预估数据
            var listQueryable = GetPKMonthPanoramaQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();

            var CourseBaseList = _db.Queryable<CourseBase>()
                .Where(x => x.Status == 1).ToList();

            // 获取当前月份的第一天
            DateTime firstDayOfMonth = new DateTime(input.Year, input.Month, 1);
            // 获取当前月份的最后一天
            DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);
            #endregion
            //返回信息
            var result = new List<GetPKMonthPanoramaOutPut>();
            #region 计划排班
            decimal studentCount = 0;
            decimal revenue = 0;
            //只显示在月内的数据，跨月就算到下个月，开始时间在这个月的也算进去
            studentCount = listViewDto.Where(q => DateTime.Parse(q.TrainEndDate).Month == input.Month).Sum(p => p.EstimatedStudentCount);
            revenue = listViewDto.Where(q => DateTime.Parse(q.TrainEndDate).Month == input.Month).Sum(p => p.EstimatedRevenue);
            if (listViewDto.Count() > 0)
            {
                List<GetPKMonthPanoramaOutPut.detailList> myList = new List<GetPKMonthPanoramaOutPut.detailList>();
                // 添加元素到myList
                for (int i = 1; i < 31; i++)
                {
                    var obj = new GetPKMonthPanoramaOutPut.detailList();
                    obj.date1 = "date" + i;
                    myList.Add(obj);
                }

                for (int i = 0; i < listViewDto.Count(); i++)
                {
                    var newlist = new GetPKMonthPanoramaOutPut();
                    //返回结果
                    newlist.tjTitle = "计划排班";
                    newlist.tjNum = $"{listViewDto.Count()} ";
                    DateTime start = Convert.ToDateTime(listViewDto[i].TrainStartDate);
                    DateTime end = Convert.ToDateTime(listViewDto[i].TrainEndDate);

                    string area = listViewDto[i].Area;
                    string schoolName = listViewDto[i].SchoolName;
                    if (schoolName.Contains("学校"))
                    {
                        schoolName = schoolName.Replace("学校", string.Empty);
                    }
                    //string courseName = "【" + schoolName + "】" + listViewDto[i].CourseName;
                    //string courseName = "【" + schoolName + "】" + listViewDto[i].CourseName + 
                    //    "(" + Math.Round(listViewDto[i].EstimatedStudentCount, 0) + "/" 
                    //    + Math.Round(listViewDto[i].MaxfitStudentCount, 0) + ")"
                    //                  + "!$$!预估"
                    //                  + "!$$!P";
                    string courseName =
                        (string.IsNullOrEmpty(listViewDto[i].ClassBase) ? $"【{schoolName}】" : $"【{schoolName},{listViewDto[i].ClassBase}】") +
                        $"{listViewDto[i].CourseName}" +
                        $"({Math.Round(listViewDto[i].EstimatedStudentCount, 0)}/" +
                        $"{Math.Round(listViewDto[i].MaxfitStudentCount, 0)})!$$!预估!$$!P";
                    bool idadd = true;
                    if (i > 0)
                    {
                        int t = i - 1;
                        DateTime prstart = Convert.ToDateTime(listViewDto[t].TrainStartDate);
                        DateTime prend = Convert.ToDateTime(listViewDto[t].TrainEndDate);
                        string prcourseName = listViewDto[t].CourseName;
                        string prarea = listViewDto[t].Area;
                        if (!IsOverlap(prstart, prend, start, end) && area == prarea)
                        {
                            //时间不重叠,培训认证中心/项目组相同，拼成一条
                            var daily = new GetPKMonthPanoramaOutPut.detailList();
                            bool isdaily = false;
                            for (var date = Convert.ToDateTime(start); date <= Convert.ToDateTime(end); date = date.AddDays(1))
                            {
                                DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                                if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                                {
                                    string dateV = "date" + dateStr.Day;
                                    // 通过属性名称为指定列赋值
                                    PropertyInfo property = typeof(GetPKMonthPanoramaOutPut.detailList).GetProperty(dateV);
                                    if (property != null && property.CanWrite)
                                    {
                                        foreach (var item in myList)
                                        {
                                            if (property.GetValue(item) == null && !isdaily)
                                            {
                                                property.SetValue(item, courseName, null);
                                                newlist.dailyList = item;
                                            }
                                            else
                                            {
                                                isdaily = true;
                                                property.SetValue(daily, courseName, null);
                                            }
                                        }
                                    }
                                }
                            }
                            if (isdaily)
                            {
                                newlist.dailyList = daily;
                                myList.Clear();
                                myList.Add(daily);
                                result.Add(newlist);
                            }
                            idadd = false;
                        }
                        else
                        {
                            idadd = true;
                        }
                    }
                    if (idadd)
                    {
                        var daily = new GetPKMonthPanoramaOutPut.detailList();
                        for (var date = Convert.ToDateTime(start); date <= Convert.ToDateTime(end); date = date.AddDays(1))
                        {
                            DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                            if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                            {
                                string dateV = "date" + dateStr.Day;
                                if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                                {
                                    //遍历类中属性
                                    foreach (System.Reflection.PropertyInfo info in daily.GetType().GetProperties())
                                    {
                                        var value = daily.GetType().GetProperty(info.Name).Name;
                                        if (value == dateV)
                                        {
                                            info.SetValue(daily, courseName, null);
                                        }
                                    }
                                }
                            }
                        }
                        newlist.dailyList = daily;
                        myList.Clear();
                        myList.Add(daily);
                        result.Add(newlist);
                    }
                }
            }
            #endregion
            #region 实际排班
            decimal studentCount_real = 0;
            decimal revenue_real = 0;
            //只显示在月内的数据，跨月就算到下个月，开始时间在这个月的也算进去
            studentCount_real = listViewDto_real.Where(q => DateTime.Parse(q.TrainEndDate).Month == input.Month).Sum(p => p.EstimatedStudentCount);
            revenue_real = listViewDto_real.Where(q => DateTime.Parse(q.TrainEndDate).Month == input.Month).Sum(p => p.EstimatedRevenue);
            if (listViewDto_real.Count() > 0)
            {
                List<GetPKMonthPanoramaOutPut.detailList> myList_real = new List<GetPKMonthPanoramaOutPut.detailList>();
                // 添加元素到myList
                for (int i = 1; i < 31; i++)
                {
                    var obj = new GetPKMonthPanoramaOutPut.detailList();
                    obj.date1 = "date" + i;
                    myList_real.Add(obj);
                }

                for (int i = 0; i < listViewDto_real.Count(); i++)
                {
                    var newlist = new GetPKMonthPanoramaOutPut();
                    //返回结果
                    newlist.tjTitle = "实际排班";
                    newlist.tjNum = $"{listViewDto_real.Count()}  ";
                    DateTime start = Convert.ToDateTime(listViewDto_real[i].TrainStartDate);
                    DateTime end = Convert.ToDateTime(listViewDto_real[i].TrainEndDate);

                    string area = listViewDto_real[i].Area;
                    string schoolName = listViewDto_real[i].SchoolName;

                    var curCourseBase = CourseBaseList.Find(p => p.CourseCode == listViewDto_real[i].CourseCode);
                    string fullStudentCount = curCourseBase == null ? string.Empty : string.Empty;
                    if (schoolName.Contains("学校"))
                    {
                        schoolName = schoolName.Replace("学校", string.Empty);
                    }
                    //string courseName = "【" + schoolName + "】" + listViewDto_real[i].CourseName +
                    //"(" + Math.Round(listViewDto_real[i].EstimatedStudentCount, 0) + "/" +
                    //Math.Round(listViewDto_real[i].MaxfitStudentCount, 0) + ")"
                    //                   + "!$$!" + listViewDto_real[i].ChangeTypeCode
                    //                   + "!$$!R";
                    string courseName =
                        (string.IsNullOrEmpty(listViewDto_real[i].ClassBase) ? $"【{schoolName}】" : $"【{schoolName},{listViewDto_real[i].ClassBase}】") +
                        $"{listViewDto_real[i].CourseName}" +
                        $"({Math.Round(listViewDto_real[i].EstimatedStudentCount, 0)}/" +
                        $"{Math.Round(listViewDto_real[i].MaxfitStudentCount, 0)})!$$!{listViewDto_real[i].ChangeTypeCode}!$$!R";
                    bool idadd = true;
                    if (i > 0)
                    {
                        int t = i - 1;
                        DateTime prstart = Convert.ToDateTime(listViewDto_real[t].TrainStartDate);
                        DateTime prend = Convert.ToDateTime(listViewDto_real[t].TrainEndDate);
                        string prcourseName = listViewDto_real[t].CourseName;
                        string prarea = listViewDto_real[t].Area;
                        if (!IsOverlap(prstart, prend, start, end) && area == prarea)
                        {
                            //时间不重叠,培训认证中心/项目组相同，拼成一条
                            var daily = new GetPKMonthPanoramaOutPut.detailList();
                            bool isdaily = false;
                            for (var date = Convert.ToDateTime(start); date <= Convert.ToDateTime(end); date = date.AddDays(1))
                            {
                                DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                                if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                                {
                                    string dateV = "date" + dateStr.Day;
                                    // 通过属性名称为指定列赋值
                                    PropertyInfo property = typeof(GetPKMonthPanoramaOutPut.detailList).GetProperty(dateV);
                                    if (property != null && property.CanWrite)
                                    {
                                        foreach (var item in myList_real)
                                        {
                                            if (property.GetValue(item) == null && !isdaily)
                                            {
                                                property.SetValue(item, courseName, null);
                                                newlist.dailyList = item;
                                            }
                                            else
                                            {
                                                isdaily = true;
                                                property.SetValue(daily, courseName, null);
                                            }
                                        }
                                    }
                                }
                            }
                            if (isdaily)
                            {
                                newlist.dailyList = daily;
                                myList_real.Clear();
                                myList_real.Add(daily);
                                result.Add(newlist);
                            }
                            idadd = false;
                        }
                        else
                        {
                            idadd = true;
                        }
                    }
                    if (idadd)
                    {
                        var daily = new GetPKMonthPanoramaOutPut.detailList();
                        for (var date = Convert.ToDateTime(start); date <= Convert.ToDateTime(end); date = date.AddDays(1))
                        {
                            DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                            if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                            {
                                string dateV = "date" + dateStr.Day;
                                if (dateStr.Year == input.Year && dateStr.Month == input.Month)
                                {
                                    //遍历类中属性
                                    foreach (System.Reflection.PropertyInfo info in daily.GetType().GetProperties())
                                    {
                                        var value = daily.GetType().GetProperty(info.Name).Name;
                                        if (value == dateV)
                                        {
                                            info.SetValue(daily, courseName, null);
                                        }
                                    }
                                }
                            }
                        }
                        newlist.dailyList = daily;
                        myList_real.Clear();
                        myList_real.Add(daily);
                        result.Add(newlist);
                    }
                }
            }
            #endregion
            #region 计划汇总
            var newResult2 = new GetPKMonthPanoramaOutPut();
            newResult2.tjTitle = "预估人次";
            newResult2.tjNum = $"{studentCount}   ";
            newResult2.dailyList = getDateSumList(listViewDto, 1, input);

            var newResult3 = new GetPKMonthPanoramaOutPut();
            newResult3.tjTitle = "预估收入";
            newResult3.tjNum = $"{Math.Round(revenue, 0)}    ";
            newResult3.dailyList = getDateSumList(listViewDto, 2, input);
            result.Add(newResult2);
            result.Add(newResult3);
            #endregion
            #region 实际汇总
            var newResult2_real = new GetPKMonthPanoramaOutPut();
            newResult2_real.tjTitle = "实际人次";
            newResult2_real.tjNum = $"{studentCount_real}     ";
            newResult2_real.dailyList = getDateSumListReal(listViewDto_real, 1, input);

            var newResult3_real = new GetPKMonthPanoramaOutPut();
            newResult3_real.tjTitle = "应收收入";
            newResult3_real.tjNum = $"{Math.Round(revenue_real, 0)}      ";
            newResult3_real.dailyList = getDateSumListReal(listViewDto_real, 2, input);
            result.Add(newResult2_real);
            result.Add(newResult3_real);
            #endregion
            return result;

        }
        private ISugarQueryable<PKSubmittedByPrincipalDetailReal> GetPKMonthRealQueryable(PKMonthPanoramaInput input)
        {
            if (input.Year != 0 && input.Month != 0)
            {
                var listQueryable = _db.Queryable<PKSubmittedByPrincipalReal, PKSubmittedByPrincipalDetailReal, KeyValues>(
                    (a, p, k) => new JoinQueryInfos(JoinType.Left, a.InstanceNumber == p.InstanceNumber, JoinType.Left, p.SchoolName == k.Name))
                        .WhereIF(!string.IsNullOrWhiteSpace(input.SchoolName) && input.SchoolName != "全部", (a, p, k) => p.SchoolName == input.SchoolName)
                        .WhereIF(!string.IsNullOrWhiteSpace(input.SchoolArea) && input.SchoolArea != "全部", (a, p, k) => k.ParentCode == input.SchoolArea)
                        .WhereIF(input.Year != 0, (a, p, k) => DateTime.Parse(p.TrainEndDate).Year == input.Year)
                        .WhereIF(input.Month != 0, (a, p, k) => DateTime.Parse(p.TrainEndDate).Month >= input.Month && DateTime.Parse(p.TrainStartDate).Month <= input.Month)
                        .Select((a, p, k) => new PKSubmittedByPrincipalDetailReal
                        {
                            Id=p.Id,
                            ChangeTypeCode=p.ChangeTypeCode,
                            CourseName = p.CourseName,
                            //SortNo = p.SortNo,
                            SortNo = k.Sort.Value,
                            TrainStartDate = p.TrainStartDate,
                            TrainEndDate = p.TrainEndDate,
                            EstimatedStudentCount = p.EstimatedStudentCount,
                            EstimatedRevenue = p.EstimatedRevenue,
                            CreateTime = p.CreateTime,
                            SchoolName = p.SchoolName,
                            MaxfitStudentCount=p.MaxfitStudentCount,
                            Area = p.Area,
                            ClassBase = p.ClassBase,
                        }).MergeTable().OrderBy(k => k.SortNo).OrderBy(a => a.Area).OrderBy(a => a.SchoolName).OrderBy(a => a.SortNo);

                return listQueryable;
            }
            return null;
        }

        public GetPKMonthPanoramaOutPut.detailList getDateSumListReal(List<PKSubmittedByPrincipalDetailReal> list, int type, PKMonthPanoramaInput input)
        {
            var result = new GetPKMonthPanoramaOutPut.detailList();
            //预估人次、预付收入合计取值按照课程最后一天去合计，存在跨月情况，统计到下个月去合计
            //如果存在跨周末、跨月的可能性，以最后一天为准计算
            var dailylist = new List<GetPKMonthPanoramaOutPut.detailList>();
            list = list.OrderBy(p => p.TrainEndDate).ToList();
            //如果上一条和下一条的周末相同，就把它们的值累计相加，赋给这周的每一天
            DateTime lastDayOfWeekNew = DateTime.Now;
            decimal studentCount = 0;
            decimal estimatedRevenue = 0;
            for (int i = 0; i < list.Count; i++)
            {
                //星期一为第一天
                DateTime currentDate = DateTime.Parse(list[i].TrainEndDate);
                //如果不是在查询的这个月中，不统计
                if (currentDate.Year == input.Year && currentDate.Month == input.Month)
                {
                    int weeknow = Convert.ToInt32(currentDate.DayOfWeek);

                    //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。
                    weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
                    int daydiff = (-1) * weeknow;
                    //本周第一天
                    DateTime firstDayOfWeek = currentDate.AddDays(daydiff);

                    //星期天为最后一天
                    int weeknow2 = Convert.ToInt32(currentDate.DayOfWeek);
                    weeknow2 = (weeknow2 == 0 ? 7 : weeknow2);
                    int daydiff2 = (7 - weeknow2);
                    //本周最后一天
                    DateTime lastDayOfWeek = currentDate.AddDays(daydiff2);
                    DateTime lastDayOfWeek2 = currentDate.AddDays(daydiff2);
                    // 获取当前月份的第一天
                    DateTime firstDayOfMonth = new DateTime(input.Year, input.Month, 1);
                    // 获取当前月份的最后一天
                    DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

                    var day = currentDate.DayOfWeek;
                    if (day != DayOfWeek.Sunday && day != DayOfWeek.Saturday)
                    {
                        lastDayOfWeek = currentDate.AddDays(5 - weeknow2);//默认按五天为一个阶段
                    }
                    if (day == DayOfWeek.Sunday)
                    {
                        //判断是否为周末
                        lastDayOfWeek = currentDate;
                    }
                    if (day == DayOfWeek.Saturday)
                    {
                        //判断是否为周六
                        lastDayOfWeek = currentDate.AddDays(6 - weeknow2);
                    }
                    if (currentDate == lastDayOfMonth)
                    {
                        //是否为这个月的最后一天
                        lastDayOfWeek = lastDayOfMonth;
                    }
                    if (lastDayOfWeek.Month != firstDayOfWeek.Month && lastDayOfWeek.Day < firstDayOfWeek.Day)
                    {
                        //跨月又跨周的情况是取这个月的最后一天
                        TimeSpan ts = lastDayOfMonth - lastDayOfWeek;
                        double dbl = ts.TotalDays;
                        int intDow = Convert.ToInt32(lastDayOfMonth.DayOfWeek);

                        if (intDow == 0) intDow = 7;

                        if (dbl >= 7 || dbl >= intDow)
                        {
                        }
                        else
                        {
                            lastDayOfWeek = lastDayOfMonth;
                        }
                    }
                    if (firstDayOfWeek.Month != lastDayOfWeek.Month)
                    {
                        //一周中有不同月份的时间，取相同月份
                        firstDayOfWeek = lastDayOfWeek.AddDays(-lastDayOfWeek.Day + 1);
                    }
                    //如果上一条和下一条的周末相同，就把它们的值累计相加，赋给这周的每一天
                    if (i > 0)
                    {
                        if (lastDayOfWeekNew == lastDayOfWeek2)
                        {
                            if (type == 1)
                            {
                                studentCount += list[i].EstimatedStudentCount;
                            }
                            else
                            {
                                estimatedRevenue += list[i].EstimatedRevenue;
                            }
                            if (dailylist.Count > 0)
                            {
                                dailylist.RemoveAt(dailylist.Count - 1);
                            }
                        }
                        else
                        {
                            if (type == 1)
                            {
                                studentCount = list[i].EstimatedStudentCount;
                            }
                            else
                            {
                                estimatedRevenue = list[i].EstimatedRevenue;
                            }
                        }
                        lastDayOfWeekNew = lastDayOfWeek2;
                    }
                    else
                    {
                        if (type == 1)
                        {
                            studentCount = list[i].EstimatedStudentCount;
                        }
                        else
                        {
                            estimatedRevenue = list[i].EstimatedRevenue;
                        }
                        lastDayOfWeekNew = lastDayOfWeek2;
                    }

                    var daily = new GetPKMonthPanoramaOutPut.detailList();
                    if (firstDayOfWeek.Day < lastDayOfWeek.Day)
                    {
                        //同一个月
                        for (var date = firstDayOfWeek; date <= lastDayOfWeek; date = date.AddDays(1))
                        {
                            DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                            string dateV = "date" + dateStr.Day;
                            decimal num = 0;
                            //遍历类中属性
                            foreach (System.Reflection.PropertyInfo info in daily.GetType().GetProperties())
                            {
                                //通过属性名称获取属性的值
                                var value = daily.GetType().GetProperty(info.Name).Name;
                                if (value == dateV)
                                {
                                    if (type == 1)
                                    {
                                        num = studentCount;
                                    }
                                    else
                                    {
                                        num = estimatedRevenue;
                                    }
                                    // 获取属性信息
                                    //PropertyInfo propInfo = typeof(GetPKMonthPanoramaOutPut.detailList).GetProperty(dateV);
                                    //if (propInfo != null && propInfo.CanRead && propInfo.CanWrite)
                                    //{
                                    //    // 设置属性值
                                    //    propInfo.SetValue(daily, num.ToString());
                                    //}
                                    info.SetValue(daily, num.ToString(), null);
                                }
                            }
                        }
                        dailylist.Add(daily);
                    }
                    else
                    {
                        //不同月
                        for (var date = lastDayOfWeek; date <= lastDayOfWeek; date = date.AddDays(1))
                        {
                            DateTime dateStr = Convert.ToDateTime(date.ToString("yyyy-MM-dd"));
                            string dateV = "date" + dateStr.Day;
                            decimal num = 0;

                            //遍历类中属性
                            foreach (System.Reflection.PropertyInfo info in daily.GetType().GetProperties())
                            {
                                //通过属性名称获取属性的值
                                var value = daily.GetType().GetProperty(info.Name).Name;
                                if (value == dateV)
                                {
                                    if (type == 1)
                                    {
                                        num = studentCount;
                                    }
                                    else
                                    {
                                        num = estimatedRevenue;
                                    }
                                    info.SetValue(daily, num.ToString(), null);
                                }
                            }
                        }
                        dailylist.Add(daily);
                    }
                }
            }

            //统计每天的人数和预估收入相加
            decimal date1 = 0, date2 = 0, date3 = 0, date4 = 0, date5 = 0, date6 = 0, date7 = 0, date8 = 0, date9 = 0, date10 = 0, date11 = 0, date12 = 0
                , date13 = 0, date14 = 0, date15 = 0, date16 = 0, date17 = 0, date18 = 0, date19 = 0, date20 = 0, date21 = 0, date22 = 0, date23 = 0
                , date24 = 0, date25 = 0, date26 = 0, date27 = 0, date28 = 0, date29 = 0, date30 = 0, date31 = 0;
            for (int i = 0; i < dailylist.Count; i++)
            {
                if (dailylist[i].date1 != null)
                {
                    date1 += decimal.Parse(dailylist[i].date1);
                    result.date1 = date1.ToString();
                }
                if (dailylist[i].date2 != null)
                {
                    date2 += decimal.Parse(dailylist[i].date2);
                    result.date2 = date2.ToString();
                }
                if (dailylist[i].date3 != null)
                {
                    date3 += decimal.Parse(dailylist[i].date3);
                    result.date3 = date3.ToString();
                }
                if (dailylist[i].date4 != null)
                {
                    date4 += decimal.Parse(dailylist[i].date4);
                    result.date4 = date4.ToString();
                }
                if (dailylist[i].date5 != null)
                {
                    date5 += decimal.Parse(dailylist[i].date5);
                    result.date5 = date5.ToString();
                }
                if (dailylist[i].date6 != null)
                {
                    date6 += decimal.Parse(dailylist[i].date6);
                    result.date6 = date6.ToString();
                }
                if (dailylist[i].date7 != null)
                {
                    date7 += decimal.Parse(dailylist[i].date7);
                    result.date7 = date7.ToString();
                }
                if (dailylist[i].date8 != null)
                {
                    date8 += decimal.Parse(dailylist[i].date8);
                    result.date8 = date8.ToString();
                }
                if (dailylist[i].date9 != null)
                {
                    date9 += decimal.Parse(dailylist[i].date9);
                    result.date9 = date9.ToString();
                }
                if (dailylist[i].date10 != null)
                {
                    date10 += decimal.Parse(dailylist[i].date10);
                    result.date10 = date10.ToString();
                }
                if (dailylist[i].date11 != null)
                {
                    date11 += decimal.Parse(dailylist[i].date11);
                    result.date11 = date11.ToString();
                }
                if (dailylist[i].date12 != null)
                {
                    date12 += decimal.Parse(dailylist[i].date12);
                    result.date12 = date12.ToString();
                }
                if (dailylist[i].date13 != null)
                {
                    date13 += decimal.Parse(dailylist[i].date13);
                    result.date13 = date13.ToString();
                }
                if (dailylist[i].date14 != null)
                {
                    date14 += decimal.Parse(dailylist[i].date14);
                    result.date14 = date14.ToString();
                }
                if (dailylist[i].date15 != null)
                {
                    date15 += decimal.Parse(dailylist[i].date15);
                    result.date15 = date15.ToString();
                }
                if (dailylist[i].date16 != null)
                {
                    date16 += decimal.Parse(dailylist[i].date16);
                    result.date16 = date16.ToString();
                }
                if (dailylist[i].date17 != null)
                {
                    date17 += decimal.Parse(dailylist[i].date17);
                    result.date17 = date17.ToString();
                }
                if (dailylist[i].date18 != null)
                {
                    date18 += decimal.Parse(dailylist[i].date18);
                    result.date18 = date18.ToString();
                }
                if (dailylist[i].date19 != null)
                {
                    date19 += decimal.Parse(dailylist[i].date19);
                    result.date19 = date19.ToString();
                }
                if (dailylist[i].date20 != null)
                {
                    date20 += decimal.Parse(dailylist[i].date20);
                    result.date20 = date20.ToString();
                }
                if (dailylist[i].date21 != null)
                {
                    date21 += decimal.Parse(dailylist[i].date21);
                    result.date21 = date21.ToString();
                }
                if (dailylist[i].date22 != null)
                {
                    date22 += decimal.Parse(dailylist[i].date22);
                    result.date22 = date22.ToString();
                }
                if (dailylist[i].date23 != null)
                {
                    date23 += decimal.Parse(dailylist[i].date23);
                    result.date23 = date23.ToString();
                }
                if (dailylist[i].date24 != null)
                {
                    date24 += decimal.Parse(dailylist[i].date24);
                    result.date24 = date24.ToString();
                }
                if (dailylist[i].date25 != null)
                {
                    date25 += decimal.Parse(dailylist[i].date25);
                    result.date25 = date25.ToString();
                }
                if (dailylist[i].date26 != null)
                {
                    date26 += decimal.Parse(dailylist[i].date26);
                    result.date26 = date26.ToString();
                }
                if (dailylist[i].date27 != null)
                {
                    date27 += decimal.Parse(dailylist[i].date27);
                    result.date27 = date27.ToString();
                }
                if (dailylist[i].date28 != null)
                {
                    date28 += decimal.Parse(dailylist[i].date28);
                    result.date28 = date28.ToString();
                }
                if (dailylist[i].date29 != null)
                {
                    date29 += decimal.Parse(dailylist[i].date29);
                    result.date29 = date29.ToString();
                }
                if (dailylist[i].date30 != null)
                {
                    date30 += decimal.Parse(dailylist[i].date30);
                    result.date30 = date30.ToString();
                }
                if (dailylist[i].date31 != null)
                {
                    date31 += decimal.Parse(dailylist[i].date31);
                    result.date31 = date31.ToString();
                }
            }
            #region 取整
            result.date1 = string.IsNullOrEmpty(result.date1) ? result.date1 : Math.Round(decimal.Parse(result.date1), 0).ToString();
            result.date2 = string.IsNullOrEmpty(result.date2) ? result.date2 : Math.Round(decimal.Parse(result.date2), 0).ToString();
            result.date3 = string.IsNullOrEmpty(result.date3) ? result.date3 : Math.Round(decimal.Parse(result.date3), 0).ToString();
            result.date4 = string.IsNullOrEmpty(result.date4) ? result.date4 : Math.Round(decimal.Parse(result.date4), 0).ToString();
            result.date5 = string.IsNullOrEmpty(result.date5) ? result.date5 : Math.Round(decimal.Parse(result.date5), 0).ToString();
            result.date6 = string.IsNullOrEmpty(result.date6) ? result.date6 : Math.Round(decimal.Parse(result.date6), 0).ToString();
            result.date7 = string.IsNullOrEmpty(result.date7) ? result.date7 : Math.Round(decimal.Parse(result.date7), 0).ToString();
            result.date8 = string.IsNullOrEmpty(result.date8) ? result.date8 : Math.Round(decimal.Parse(result.date8), 0).ToString();
            result.date9 = string.IsNullOrEmpty(result.date9) ? result.date9 : Math.Round(decimal.Parse(result.date9), 0).ToString();
            result.date10 = string.IsNullOrEmpty(result.date10) ? result.date10 : Math.Round(decimal.Parse(result.date10), 0).ToString();
            result.date11 = string.IsNullOrEmpty(result.date11) ? result.date11 : Math.Round(decimal.Parse(result.date11), 0).ToString();
            result.date12 = string.IsNullOrEmpty(result.date12) ? result.date12 : Math.Round(decimal.Parse(result.date12), 0).ToString();
            result.date13 = string.IsNullOrEmpty(result.date13) ? result.date13 : Math.Round(decimal.Parse(result.date13), 0).ToString();
            result.date14 = string.IsNullOrEmpty(result.date14) ? result.date14 : Math.Round(decimal.Parse(result.date14), 0).ToString();
            result.date15 = string.IsNullOrEmpty(result.date15) ? result.date15 : Math.Round(decimal.Parse(result.date15), 0).ToString();
            result.date16 = string.IsNullOrEmpty(result.date16) ? result.date16 : Math.Round(decimal.Parse(result.date16), 0).ToString();
            result.date17 = string.IsNullOrEmpty(result.date17) ? result.date17 : Math.Round(decimal.Parse(result.date17), 0).ToString();
            result.date18 = string.IsNullOrEmpty(result.date18) ? result.date18 : Math.Round(decimal.Parse(result.date18), 0).ToString();
            result.date19 = string.IsNullOrEmpty(result.date19) ? result.date19 : Math.Round(decimal.Parse(result.date19), 0).ToString();
            result.date20 = string.IsNullOrEmpty(result.date20) ? result.date20 : Math.Round(decimal.Parse(result.date20), 0).ToString();
            result.date21 = string.IsNullOrEmpty(result.date21) ? result.date21 : Math.Round(decimal.Parse(result.date21), 0).ToString();
            result.date22 = string.IsNullOrEmpty(result.date22) ? result.date22 : Math.Round(decimal.Parse(result.date22), 0).ToString();
            result.date23 = string.IsNullOrEmpty(result.date23) ? result.date23 : Math.Round(decimal.Parse(result.date23), 0).ToString();
            result.date24 = string.IsNullOrEmpty(result.date24) ? result.date24 : Math.Round(decimal.Parse(result.date24), 0).ToString();
            result.date25 = string.IsNullOrEmpty(result.date25) ? result.date25 : Math.Round(decimal.Parse(result.date25), 0).ToString();
            result.date26 = string.IsNullOrEmpty(result.date26) ? result.date26 : Math.Round(decimal.Parse(result.date26), 0).ToString();
            result.date27 = string.IsNullOrEmpty(result.date27) ? result.date27 : Math.Round(decimal.Parse(result.date27), 0).ToString();
            result.date28 = string.IsNullOrEmpty(result.date28) ? result.date28 : Math.Round(decimal.Parse(result.date28), 0).ToString();
            result.date29 = string.IsNullOrEmpty(result.date29) ? result.date29 : Math.Round(decimal.Parse(result.date29), 0).ToString();
            result.date30 = string.IsNullOrEmpty(result.date30) ? result.date30 : Math.Round(decimal.Parse(result.date30), 0).ToString();
            result.date31 = string.IsNullOrEmpty(result.date31) ? result.date31 : Math.Round(decimal.Parse(result.date31), 0).ToString();
            #endregion
            return result;
        }
        /// <summary>
        /// 财务报表查询（实际vs预估）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetPKSubmittedByPrincipalDetailFinancialOutput>> GetPKSubmittedByPrincipalDetailFinancialSearch(PKBudgetDataInput input)
        {
            RefAsync<int> totalCount = 0;
            var listQueryable = GetDetailQueryable(input);
            var listQueryablereal = GetDetailRealQueryable(input);

            var listViewDto = listQueryable.ToList();
            var listViewDtoReal = listQueryablereal.ToList();

            var mapperListFinancial = new List<GetPKSubmittedByPrincipalDetailFinancialOutput>();
            GetPKSubmittedByPrincipalDetailFinancialOutput addone = null; 
            foreach (var Dtoitem in listViewDto)
            {
                //addone = ObjectMapper.Map<PKSubmittedByPrincipalDetail, GetPKSubmittedByPrincipalDetailFinancialOutput>(Dtoitem);
                addone = new GetPKSubmittedByPrincipalDetailFinancialOutput();
                addone.Year = Dtoitem.Year;
                addone.Month = Dtoitem.Month;
                addone.Area = Dtoitem.Area;
                addone.SchoolName = Dtoitem.SchoolName;
                addone.CourseCode = Dtoitem.CourseCode;
                addone.CourseName = Dtoitem.CourseName;
                addone.CourseNature = Dtoitem.CourseNature;
                addone.ChargeTypeCode = Dtoitem.ChargeTypeCode;
                addone.CourseTypeCode = Dtoitem.CourseTypeCode;
                addone.TeachCity = Dtoitem.TeachCity;
                addone.ClientCode = Dtoitem.ClientCode;
                addone.BU = Dtoitem.BU;
                addone.TrainingObjects = Dtoitem.TrainingObjects;
                addone.ChargeDif = Dtoitem.ChargeDif;
                addone.Amount = Dtoitem.Amount;
                addone.CourseIsNew = Dtoitem.CourseIsNew;
                addone.TrainDays = Dtoitem.TrainDays;
                addone.StandardTeacherCount = Dtoitem.StandardTeacherCount;
                addone.StandardStudentCount = Dtoitem.StandardStudentCount;
                addone.EstimatedStudentCount = Dtoitem.EstimatedStudentCount;
                addone.EstimatedNumberClasses = Dtoitem.EstimatedNumberClasses;
                addone.EstimatedRevenue = Dtoitem.EstimatedRevenue;
                addone.TeachWayCode = Dtoitem.TeachWayCode;
                

                var fetchreal = listViewDtoReal.Find(p => !string.IsNullOrEmpty(p.SourceId) && p.SourceId == Dtoitem.Id.ToString());
                if(fetchreal!=null)
                {
                    addone.RealNumberClasses = fetchreal.EstimatedNumberClasses;
                    addone.RealRevenue = fetchreal.EstimatedRevenue;
                    addone.RealStudentCount = fetchreal.EstimatedStudentCount;
                    listViewDtoReal.Remove(fetchreal);
                }
                mapperListFinancial.Add(addone);
            }
            foreach(var DtoRealitem in listViewDtoReal)
            {

                addone = new GetPKSubmittedByPrincipalDetailFinancialOutput();
                addone.Year = DtoRealitem.Year;
                addone.Month = DtoRealitem.Month;
                addone.Area = DtoRealitem.Area;
                addone.SchoolName = DtoRealitem.SchoolName;
                addone.CourseCode = DtoRealitem.CourseCode;
                addone.CourseName = DtoRealitem.CourseName;
                addone.CourseNature = DtoRealitem.CourseNature;
                addone.ChargeTypeCode = DtoRealitem.ChargeTypeCode;
                addone.CourseTypeCode = DtoRealitem.CourseTypeCode;
                addone.TeachCity = DtoRealitem.TeachCity;
                addone.ClientCode = DtoRealitem.ClientCode;
                addone.BU = DtoRealitem.BU;
                addone.TrainingObjects = DtoRealitem.TrainingObjects;
                addone.ChargeDif = DtoRealitem.ChargeDif;
                addone.Amount = DtoRealitem.Amount;
                addone.CourseIsNew = DtoRealitem.CourseIsNew;
                addone.TrainDays = DtoRealitem.TrainDays;
                addone.StandardTeacherCount = DtoRealitem.StandardTeacherCount;
                addone.StandardStudentCount = DtoRealitem.StandardStudentCount;
                addone.RealStudentCount = DtoRealitem.EstimatedStudentCount;
                addone.RealNumberClasses = DtoRealitem.EstimatedNumberClasses;
                addone.RealRevenue = DtoRealitem.EstimatedRevenue;
                addone.TeachWayCode = DtoRealitem.TeachWayCode;
                mapperListFinancial.Add(addone);
            }

            totalCount = mapperListFinancial.Count();
            int index = (input.PageIndex - 1) * input.PageSize;
            int size = input.PageSize;
            if ((input.PageIndex * input.PageSize) > totalCount)
            {
                size = totalCount - index;
            }
            var mapperListFinancialDto = mapperListFinancial.Skip(index).Take(size).ToList();
            //  var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            //var mapperList = ObjectMapper.Map<List<PKSubmittedByPrincipalDetailReal>, List<GetPKSubmittedByPrincipalDetailRealOutput>>(listViewDto);

            mapperListFinancialDto.ForEach(p =>
            {
                p.CourseTypeCode = showCourseTypeCode(p.CourseTypeCode);
                p.TeachWayCode = showTeachWayCode(p.TeachWayCode);
                p.CourseIsNew = showCourseIsNew(p.CourseIsNew);
                p.ClientCode = showClientCode(p.ClientCode);
            });
            //返回结果
            return new PagedResultDto<GetPKSubmittedByPrincipalDetailFinancialOutput>()
            {
                TotalCount = totalCount,
                Items = mapperListFinancialDto
            };
        }
        /// <summary>
        ///  校长提交明细导出(财务报表实际vs预估)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetPKSubmittedByPrincipalDetailFinancialOutput>> GetPKSubmittedByPrincipalDetailFinancial(PKBudgetDataInput input)
        {
            var listQueryable = GetDetailQueryable(input);
            var listQueryablereal = GetDetailRealQueryable(input);

            var listViewDto = listQueryable.ToList();
            var listViewDtoReal = listQueryablereal.ToList();

            var mapperListFinancial = new List<GetPKSubmittedByPrincipalDetailFinancialOutput>();
            GetPKSubmittedByPrincipalDetailFinancialOutput addone = null;
            foreach (var Dtoitem in listViewDto)
            {
                //addone = ObjectMapper.Map<PKSubmittedByPrincipalDetail, GetPKSubmittedByPrincipalDetailFinancialOutput>(Dtoitem);
                addone = new GetPKSubmittedByPrincipalDetailFinancialOutput();
                addone.Year = Dtoitem.Year;
                addone.Month = Dtoitem.Month;
                addone.Area = Dtoitem.Area;
                addone.SchoolName = Dtoitem.SchoolName;
                addone.CourseCode = Dtoitem.CourseCode;
                addone.CourseName = Dtoitem.CourseName;
                addone.CourseNature = Dtoitem.CourseNature;
                addone.ChargeTypeCode = Dtoitem.ChargeTypeCode;
                addone.CourseTypeCode = Dtoitem.CourseTypeCode;
                addone.TeachCity = Dtoitem.TeachCity;
                addone.BU = Dtoitem.BU;
                addone.ClientCode = Dtoitem.ClientCode;
                addone.TrainingObjects = Dtoitem.TrainingObjects;
                addone.ChargeDif = Dtoitem.ChargeDif;
                addone.Amount = Dtoitem.Amount;
                addone.CourseIsNew = Dtoitem.CourseIsNew;
                addone.TrainDays = Dtoitem.TrainDays;
                addone.StandardTeacherCount = Dtoitem.StandardTeacherCount;
                addone.StandardStudentCount = Dtoitem.StandardStudentCount;
                addone.EstimatedStudentCount = Dtoitem.EstimatedStudentCount;
                addone.EstimatedNumberClasses = Dtoitem.EstimatedNumberClasses;
                addone.EstimatedRevenue = Dtoitem.EstimatedRevenue;
                addone.TeachWayCode = Dtoitem.TeachWayCode;


                var fetchreal = listViewDtoReal.Find(p => !string.IsNullOrEmpty(p.SourceId) && p.SourceId == Dtoitem.Id.ToString());
                if (fetchreal != null)
                {
                    addone.RealNumberClasses = fetchreal.EstimatedNumberClasses;
                    addone.RealRevenue = fetchreal.EstimatedRevenue;
                    addone.RealStudentCount = fetchreal.EstimatedStudentCount;
                    listViewDtoReal.Remove(fetchreal);
                }
                mapperListFinancial.Add(addone);
            }
            foreach (var DtoRealitem in listViewDtoReal)
            {

                addone = new GetPKSubmittedByPrincipalDetailFinancialOutput();
                addone.Year = DtoRealitem.Year;
                addone.Month = DtoRealitem.Month;
                addone.Area = DtoRealitem.Area;
                addone.SchoolName = DtoRealitem.SchoolName;
                addone.CourseCode = DtoRealitem.CourseCode;
                addone.CourseName = DtoRealitem.CourseName;
                addone.CourseNature = DtoRealitem.CourseNature;
                addone.ChargeTypeCode = DtoRealitem.ChargeTypeCode;
                addone.CourseTypeCode = DtoRealitem.CourseTypeCode;
                addone.TeachCity = DtoRealitem.TeachCity;
                addone.BU = DtoRealitem.BU;
                addone.ClientCode = DtoRealitem.ClientCode;
                addone.TrainingObjects = DtoRealitem.TrainingObjects;
                addone.ChargeDif = DtoRealitem.ChargeDif;
                addone.Amount = DtoRealitem.Amount;
                addone.CourseIsNew = DtoRealitem.CourseIsNew;
                addone.TrainDays = DtoRealitem.TrainDays;
                addone.StandardTeacherCount = DtoRealitem.StandardTeacherCount;
                addone.StandardStudentCount = DtoRealitem.StandardStudentCount;
                addone.RealStudentCount = DtoRealitem.EstimatedStudentCount;
                addone.RealNumberClasses = DtoRealitem.EstimatedNumberClasses;
                addone.RealRevenue = DtoRealitem.EstimatedRevenue;
                addone.TeachWayCode = DtoRealitem.TeachWayCode;
                mapperListFinancial.Add(addone);
            }

            mapperListFinancial.ForEach(p =>
            {
                p.CourseTypeCode = showCourseTypeCode(p.CourseTypeCode);
                p.TeachWayCode = showTeachWayCode(p.TeachWayCode);
                p.CourseIsNew = showCourseIsNew(p.CourseIsNew);
                p.ClientCode = showClientCode(p.ClientCode);
            });
            return mapperListFinancial;
        }

        /// <summary>
        /// 排班报表查询（实际vs预估）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetPKSubmittedByPrincipalDetailSchdueOutput>> GetPKSubmittedByPrincipalDetailSchdueSearch(PKBudgetDataInput input)
        {
            RefAsync<int> totalCount = 0;
            var listQueryable = GetDetailQueryable(input);
            var listQueryablereal = GetDetailRealQueryable(input);

            var listViewDto = listQueryable.ToList();
            var listViewDtoReal = listQueryablereal.ToList();

            var mapperListFinancial = new List<GetPKSubmittedByPrincipalDetailSchdueOutput>();
            GetPKSubmittedByPrincipalDetailSchdueOutput addone = null;
            foreach (var Dtoitem in listViewDto)
            {
                //addone = ObjectMapper.Map<PKSubmittedByPrincipalDetail, GetPKSubmittedByPrincipalDetailFinancialOutput>(Dtoitem);
                addone = new GetPKSubmittedByPrincipalDetailSchdueOutput();
                addone.Year = Dtoitem.Year;
                addone.Month = Dtoitem.Month;
                addone.Area = Dtoitem.Area;
                addone.SchoolName = Dtoitem.SchoolName;
                addone.CourseCode = Dtoitem.CourseCode;
                addone.CourseName = Dtoitem.CourseName;
                addone.CourseNature = Dtoitem.CourseNature;
                addone.ChargeTypeCode = Dtoitem.ChargeTypeCode;
                addone.CourseTypeCode = Dtoitem.CourseTypeCode;
                addone.TeachCity = Dtoitem.TeachCity;
                addone.BU = Dtoitem.BU;
                addone.ClientCode = Dtoitem.ClientCode;
                addone.TrainingObjects = Dtoitem.TrainingObjects;
                addone.ChargeDif = Dtoitem.ChargeDif;
                addone.Amount = Dtoitem.Amount;
                addone.CourseIsNew = Dtoitem.CourseIsNew;
                addone.TrainDays = Dtoitem.TrainDays;
                addone.StandardTeacherCount = Dtoitem.StandardTeacherCount;
                addone.StandardStudentCount = Dtoitem.StandardStudentCount;
                addone.TrainStartDate = Dtoitem.TrainStartDate;
                addone.TrainEndDate = Dtoitem.TrainEndDate;
                addone.EstimatedStudentCount = Dtoitem.EstimatedStudentCount;
                addone.EstimatedNumberClasses = Dtoitem.EstimatedNumberClasses;
                addone.EstimatedRevenue = Dtoitem.EstimatedRevenue;
                addone.TeachWayCode = Dtoitem.TeachWayCode;
                addone.TheoryTeacher = Dtoitem.TheoryTeacher;
                addone.PracticeTeacher = Dtoitem.PracticeTeacher;
                addone.ClassBase = Dtoitem.ClassBase;

                var fetchreal = listViewDtoReal.Find(p => !string.IsNullOrEmpty(p.SourceId) && p.SourceId == Dtoitem.Id.ToString());
                if (fetchreal != null)
                {
                    addone.RealTrainStartDate = fetchreal.TrainStartDate;
                    addone.RealTrainEndDate = fetchreal.TrainEndDate;
                    addone.ChangeTypeCode = fetchreal.ChangeTypeCode;
                    addone.Changeremark = fetchreal.Changeremark;
                    addone.StandardTeacherCount = fetchreal.StandardTeacherCount;
                    addone.StandardStudentCount = fetchreal.StandardStudentCount;
                    addone.RealNumberClasses = fetchreal.EstimatedNumberClasses;
                    addone.RealRevenue = fetchreal.EstimatedRevenue;
                    addone.RealStudentCount = fetchreal.EstimatedStudentCount;
                    addone.TheoryTeacher = fetchreal.TheoryTeacher;
                    addone.PracticeTeacher = fetchreal.PracticeTeacher;
                    addone.ClassBase = fetchreal.ClassBase;
                    listViewDtoReal.Remove(fetchreal);
                }
                mapperListFinancial.Add(addone);
            }
            foreach (var DtoRealitem in listViewDtoReal)
            {
                addone = new GetPKSubmittedByPrincipalDetailSchdueOutput();
                addone.Year = DtoRealitem.Year;
                addone.Month = DtoRealitem.Month;
                addone.Area = DtoRealitem.Area;
                addone.SchoolName = DtoRealitem.SchoolName;
                addone.CourseCode = DtoRealitem.CourseCode;
                addone.CourseName = DtoRealitem.CourseName;
                addone.CourseNature = DtoRealitem.CourseNature;
                addone.ChargeTypeCode = DtoRealitem.ChargeTypeCode;
                addone.CourseTypeCode = DtoRealitem.CourseTypeCode;
                addone.TeachCity = DtoRealitem.TeachCity;
                addone.BU = DtoRealitem.BU;
                addone.ClientCode = DtoRealitem.ClientCode;
                addone.TrainingObjects = DtoRealitem.TrainingObjects;
                addone.ChargeDif = DtoRealitem.ChargeDif;
                addone.Amount = DtoRealitem.Amount;
                addone.CourseIsNew = DtoRealitem.CourseIsNew;
                addone.TrainDays = DtoRealitem.TrainDays;
                addone.StandardTeacherCount = DtoRealitem.StandardTeacherCount;
                addone.StandardStudentCount = DtoRealitem.StandardStudentCount;
                addone.RealTrainStartDate = DtoRealitem.TrainStartDate;
                addone.RealTrainEndDate = DtoRealitem.TrainEndDate;
                addone.ChangeTypeCode = DtoRealitem.ChangeTypeCode;
                addone.Changeremark = DtoRealitem.Changeremark;
                addone.RealStudentCount = DtoRealitem.EstimatedStudentCount;
                addone.RealNumberClasses = DtoRealitem.EstimatedNumberClasses;
                addone.RealRevenue = DtoRealitem.EstimatedRevenue;
                addone.TeachWayCode = DtoRealitem.TeachWayCode;
                addone.TheoryTeacher = DtoRealitem.TheoryTeacher;
                addone.PracticeTeacher = DtoRealitem.PracticeTeacher;
                addone.ClassBase = DtoRealitem.ClassBase;
                mapperListFinancial.Add(addone);
            }

            totalCount = mapperListFinancial.Count();
            int index = (input.PageIndex - 1) * input.PageSize;
            int size = input.PageSize;
            if ((input.PageIndex * input.PageSize) > totalCount)
            {
                size = totalCount - index;
            }
            var mapperListFinancialDto = mapperListFinancial.Skip(index).Take(size).ToList();
            //  var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            //var mapperList = ObjectMapper.Map<List<PKSubmittedByPrincipalDetailReal>, List<GetPKSubmittedByPrincipalDetailRealOutput>>(listViewDto);

            mapperListFinancialDto.ForEach(p =>
            {
                p.CourseTypeCode = showCourseTypeCode(p.CourseTypeCode);
                p.TeachWayCode = showTeachWayCode(p.TeachWayCode);
                p.CourseIsNew = showCourseIsNew(p.CourseIsNew);
                p.ClientCode = showClientCode(p.ClientCode);
            });
            //返回结果
            return new PagedResultDto<GetPKSubmittedByPrincipalDetailSchdueOutput>()
            {
                TotalCount = totalCount,
                Items = mapperListFinancialDto
            };
        }
        /// <summary>
        ///  校长提交明细导出(排班报表实际vs预估)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetPKSubmittedByPrincipalDetailSchdueOutput>> GetPKSubmittedByPrincipalDetailSchdue(PKBudgetDataInput input)
        {
            var listQueryable = GetDetailQueryable(input);
            var listQueryablereal = GetDetailRealQueryable(input);

            var listViewDto = listQueryable.ToList();
            var listViewDtoReal = listQueryablereal.ToList();

            var mapperListFinancial = new List<GetPKSubmittedByPrincipalDetailSchdueOutput>();
            GetPKSubmittedByPrincipalDetailSchdueOutput addone = null;
            foreach (var Dtoitem in listViewDto)
            {
                //addone = ObjectMapper.Map<PKSubmittedByPrincipalDetail, GetPKSubmittedByPrincipalDetailFinancialOutput>(Dtoitem);
                addone = new GetPKSubmittedByPrincipalDetailSchdueOutput();
                addone.Year = Dtoitem.Year;
                addone.Month = Dtoitem.Month;
                addone.Area = Dtoitem.Area;
                addone.SchoolName = Dtoitem.SchoolName;
                addone.CourseCode = Dtoitem.CourseCode;
                addone.CourseName = Dtoitem.CourseName;
                addone.CourseNature = Dtoitem.CourseNature;
                addone.ChargeTypeCode = Dtoitem.ChargeTypeCode;
                addone.CourseTypeCode = Dtoitem.CourseTypeCode;
                addone.TeachCity = Dtoitem.TeachCity;
                addone.BU = Dtoitem.BU;
                addone.ClientCode = Dtoitem.ClientCode;
                addone.TrainingObjects = Dtoitem.TrainingObjects;
                addone.ChargeDif = Dtoitem.ChargeDif;
                addone.Amount = Dtoitem.Amount;
                addone.CourseIsNew = Dtoitem.CourseIsNew;
                addone.TrainDays = Dtoitem.TrainDays;
                addone.StandardTeacherCount = Dtoitem.StandardTeacherCount;
                addone.StandardStudentCount = Dtoitem.StandardStudentCount;
                addone.TrainStartDate = Dtoitem.TrainStartDate;
                addone.TrainEndDate = Dtoitem.TrainEndDate;
                addone.EstimatedStudentCount = Dtoitem.EstimatedStudentCount;
                addone.EstimatedNumberClasses = Dtoitem.EstimatedNumberClasses;
                addone.EstimatedRevenue = Dtoitem.EstimatedRevenue;
                addone.TeachWayCode = Dtoitem.TeachWayCode;
                addone.TheoryTeacher = Dtoitem.TheoryTeacher;
                addone.PracticeTeacher = Dtoitem.PracticeTeacher;


                var fetchreal = listViewDtoReal.Find(p => !string.IsNullOrEmpty(p.SourceId) && p.SourceId == Dtoitem.Id.ToString());
                if (fetchreal != null)
                {
                    addone.RealTrainStartDate = fetchreal.TrainStartDate;
                    addone.RealTrainEndDate = fetchreal.TrainEndDate;
                    addone.RealNumberClasses = fetchreal.EstimatedNumberClasses;
                    addone.RealRevenue = fetchreal.EstimatedRevenue;
                    addone.RealStudentCount = fetchreal.EstimatedStudentCount;
                    addone.ChangeTypeCode = fetchreal.ChangeTypeCode;
                    addone.Changeremark = fetchreal.Changeremark;
                    addone.StandardTeacherCount = fetchreal.StandardTeacherCount;
                    addone.StandardStudentCount = fetchreal.StandardStudentCount;
                    addone.TheoryTeacher = fetchreal.TheoryTeacher;
                    addone.PracticeTeacher = fetchreal.PracticeTeacher;
                    listViewDtoReal.Remove(fetchreal);
                }
                mapperListFinancial.Add(addone);
            }
            foreach (var DtoRealitem in listViewDtoReal)
            {

                addone = new GetPKSubmittedByPrincipalDetailSchdueOutput();
                addone.Year = DtoRealitem.Year;
                addone.Month = DtoRealitem.Month;
                addone.Area = DtoRealitem.Area;
                addone.SchoolName = DtoRealitem.SchoolName;
                addone.CourseCode = DtoRealitem.CourseCode;
                addone.CourseName = DtoRealitem.CourseName;
                addone.CourseNature = DtoRealitem.CourseNature;
                addone.ChargeTypeCode = DtoRealitem.ChargeTypeCode;
                addone.CourseTypeCode = DtoRealitem.CourseTypeCode;
                addone.TeachCity = DtoRealitem.TeachCity;
                addone.BU = DtoRealitem.BU;
                addone.ClientCode = DtoRealitem.ClientCode;
                addone.TrainingObjects = DtoRealitem.TrainingObjects;
                addone.ChargeDif = DtoRealitem.ChargeDif;
                addone.Amount = DtoRealitem.Amount;
                addone.CourseIsNew = DtoRealitem.CourseIsNew;
                addone.TrainDays = DtoRealitem.TrainDays;
                addone.StandardTeacherCount = DtoRealitem.StandardTeacherCount;
                addone.StandardStudentCount = DtoRealitem.StandardStudentCount;
                addone.ChangeTypeCode = DtoRealitem.ChangeTypeCode;
                addone.Changeremark = DtoRealitem.Changeremark;
                addone.RealTrainStartDate = DtoRealitem.TrainStartDate;
                addone.RealTrainEndDate = DtoRealitem.TrainEndDate;
                addone.RealStudentCount = DtoRealitem.EstimatedStudentCount;
                addone.RealNumberClasses = DtoRealitem.EstimatedNumberClasses;
                addone.RealRevenue = DtoRealitem.EstimatedRevenue;
                addone.TeachWayCode = DtoRealitem.TeachWayCode;
                addone.TheoryTeacher = DtoRealitem.TheoryTeacher;
                addone.PracticeTeacher = DtoRealitem.PracticeTeacher;
                mapperListFinancial.Add(addone);
            }

            mapperListFinancial.ForEach(p =>
            {
                p.CourseTypeCode = showCourseTypeCode(p.CourseTypeCode);
                p.TeachWayCode = showTeachWayCode(p.TeachWayCode);
                p.CourseIsNew = showCourseIsNew(p.CourseIsNew);
                p.ClientCode = showClientCode(p.ClientCode);
            });
            return mapperListFinancial;
        }
        /// <summary>
        /// 财务报表排班报表取实际明细数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<PKSubmittedByPrincipalDetailReal> GetDetailRealQueryable(PKBudgetDataInput input)
        {
            var listQueryable = _db.Queryable<PKSubmittedByPrincipalReal, PKSubmittedByPrincipalDetailReal>((b, p) =>
                  new JoinQueryInfos(JoinType.Inner, b.InstanceNumber == p.InstanceNumber))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.Year), (b, p) => p.Year == input.Year)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.Month), (b, p) => p.Month == input.Month)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.SchoolName) && input.SchoolName != "全部", (b, p) => p.SchoolName == input.SchoolName)
                    .WhereIF(!string.IsNullOrWhiteSpace(input.Area) && input.Area != "全部", (b, p) => p.Area == input.Area)
                     .Select((b, p) => new PKSubmittedByPrincipalDetailReal
                     {
                         Id = p.Id,
                         // InstanceNumber = p.InstanceNumber,
                         Area = p.Area,
                         SchoolName = p.SchoolName,
                         SortNo = p.SortNo,
                         Year = p.Year,
                         Month = p.Month,
                         CourseCode = p.CourseCode,
                         CourseName = p.CourseName,
                         Amount = p.Amount,
                         CourseNature = p.CourseNature,
                         ChargeTypeCode = p.ChargeTypeCode,
                         CourseTypeCode = p.CourseTypeCode,
                         TeachWayCode = p.TeachWayCode,
                         TrainingObjects = p.TrainingObjects,
                         ChargeWay = p.ChargeWay,
                         CourseIsNew = p.CourseIsNew,
                         StandardTeacherCount = p.StandardTeacherCount,
                         StandardStudentCount = p.StandardStudentCount,
                         ClientCode = p.ClientCode,
                         BU = p.BU,
                         TrainStartDate = p.TrainStartDate,
                         TrainEndDate = p.TrainEndDate,
                         ChangeTypeCode = p.ChangeTypeCode,
                         Changeremark = p.Changeremark,
                         TrainDays = p.TrainDays,
                         TeachCity = p.TeachCity,
                         EstimatedStudentCount = p.EstimatedStudentCount,
                         EstimatedNumberClasses = p.EstimatedNumberClasses,
                         ChargeDif = p.ChargeDif,
                         EstimatedRevenue = p.EstimatedRevenue,
                         CreateTime = p.CreateTime,
                         PracticeTeacher = p.PracticeTeacher,
                         TheoryTeacher = p.TheoryTeacher,
                         SourceId = p.SourceId,
                         ClassBase = p.ClassBase,
                     }).MergeTable().OrderBy(p => p.CreateTime, OrderByType.Desc).OrderBy(p => p.SortNo);

            return listQueryable;
        }
        #endregion
        #region 假期维护
        /// <summary>
        /// 获取假期数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<ExportHoliday>> GetHolidays(HolidaySearchDto input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();

            var mapperList = ObjectMapper.Map<List<PKHolidays>, List<ExportHoliday>>(listViewDto);
            mapperList.ForEach(p =>
            {
                p.HolidayDate = DateTime.Parse(p.HolidayDate.ToString()).ToString("yyyy-MM-dd");
                //p.Status == "1" ? "节假日" : "工作日";
            });
            return mapperList;
        }
        public async Task<ExportHoliday> GetHolidaysDetail(HolidaySearchDto input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.FirstAsync();
            if (listViewDto != null)
            {
                listViewDto.HolidayDate = DateTime.Parse(listViewDto.HolidayDate.ToString()).ToString("yyyy-MM-dd");
                var mapperList = ObjectMapper.Map<PKHolidays, ExportHoliday>(listViewDto);
                return mapperList;
            }
            return null;
        }

        /// <summary>
        /// 获取Queryable(报表展现)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<PKHolidays> GetQueryable(HolidaySearchDto input)
        {
            var listQueryable = _db.Queryable<PKHolidays>()
                    .WhereIF(!string.IsNullOrEmpty(input.holidayDate), (x) => x.HolidayDate == input.holidayDate)
                     .WhereIF(input.year != 0, (x) => x.HolidayYear == input.year)
                     .WhereIF(input.month != 0, (x) => x.HolidayMonth == input.month)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.status), (x) => x.Status == int.Parse(input.status))
                     .OrderBy(x => x.HolidayDate)
                     .OrderBy(x => x.Status);

            return listQueryable;
        }
        /// <summary>
        /// 新增假期
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task AddHoliday(HolidayInput input)
        {
            var editdata = _db.Queryable<PKHolidays>().Where(t => t.HolidayDate == input.HolidayDate).First();
            var convertModel = ObjectMapper.Map<HolidayInput, PKHolidays>(input);
            if (editdata == null)
            {
                await _db.Insertable(convertModel).ExecuteCommandAsync();
            }
            else
            {
                await _db.Updateable(convertModel).ExecuteCommandAsync();
            }
        }

        /// <summary>
        /// 假期维护导出
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<ExportHoliday>> ExportHoliday(HolidaySearchDto input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();

            var mapperList = ObjectMapper.Map<List<PKHolidays>, List<ExportHoliday>>(listViewDto);
            mapperList.ForEach(p =>
            {
                p.HolidayDate = DateTime.Parse(p.HolidayDate.ToString()).ToString("yyyy-MM-dd");
                p.Status = p.Status == "1" ? "节假日" : "工作日";
            });
            return mapperList;
        }

        /// <summary>
        /// 假期维护导入
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public async Task<ImportResultExt<ExportHoliday>> ImportProcess(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            var rst = await _importer.Import<ExportHoliday>(stream);
            var importData = rst.Data;
            string errorStr = string.Empty;
            if (!rst.HasError)
            {
                //验证是否有重复数据和错误数据

                // 业务数据处理
                var detail = _db.Queryable<PKHolidays>().ToList();
                List<PKHolidays> addList = new List<PKHolidays>(); // 新增
                List<PKHolidays> editList = new List<PKHolidays>(); // 更新
                foreach (var item in importData)
                {
                    if (item.Status == null || item.HolidayDate == null)
                    {
                        errorStr = "日期,节假类型不能为空";
                        continue;
                    }
                    else
                    {

                        if (item.Status != "节假日" && item.Status != "工作日")
                        {
                            errorStr = "节假类型填写为节假日/工作日两种，请检查";
                            continue;
                        }
                        // 格式化DateTime对象为yyyy-MM-dd格式
                        string HolidayDate = DateTime.Parse(item.HolidayDate.ToString()).ToString("yyyy-MM-dd");

                        var oldDetail = detail.Where(x => x.HolidayDate == HolidayDate).FirstOrDefault();
                        string[] sArray = HolidayDate.ToString().Split("-");
                        string year = sArray[0];
                        string month = sArray[1];
                        string day = sArray[2];
                        if (month.Length > 1)
                        {
                            if (month.StartsWith("0"))
                            {
                                month = month.Substring(1, month.Length - 1);
                            }
                            if (day.StartsWith("0"))
                            {
                                day = day.Substring(1, day.Length - 1);
                            }
                        }
                        if (oldDetail != null)
                        {
                            item.OperationType = "2";
                            var ishave2 = editList.Where(x => x.HolidayDate == HolidayDate).ToList();
                            if (ishave2.Count >= 1)
                            {
                                errorStr += "日期" + HolidayDate + "有重复数据，请检查；";
                                continue;
                            }
                        }
                        else
                        {
                            item.OperationType = "1";
                            var ishave = addList.Where(x => x.HolidayDate == HolidayDate).ToList();
                            if (ishave.Count >= 1)
                            {
                                errorStr += "日期" + HolidayDate + "有重复数据，请检查；";
                                continue;
                            }
                        }
                        PKHolidays PKHolidays = new PKHolidays();
                        PKHolidays.HolidayDate = HolidayDate;
                        PKHolidays.HolidayYear = int.Parse(year);
                        PKHolidays.HolidayMonth = int.Parse(month);
                        PKHolidays.HolidayDay = int.Parse(day);
                        PKHolidays.Status = item.Status == "节假日" ? 1 : 0;
                        PKHolidays.Remark = item.Remark;
                        if (item.OperationType == "1")
                        {
                            addList.Add(PKHolidays);
                        }
                        else
                        {
                            editList.Add(PKHolidays);
                        }
                    }
                }
                if (string.IsNullOrEmpty(errorStr))
                {
                    if (addList.Count > 0)
                    {
                        await _db.Insertable(addList).ExecuteCommandAsync();
                    }
                    if (editList.Count > 0)
                    {
                        await _db.Updateable(editList).ExecuteCommandAsync();
                    }
                }
            }

            var resp = new ImportResultExt<ExportHoliday>()
            {
                Data = importData,
                Exception = string.IsNullOrEmpty(errorStr) ? null : new Exception(errorStr),
                RowErrors = rst.RowErrors,
                TemplateErrors = rst.TemplateErrors,
            };
            return resp;
        }

        public async Task SaveAllHoliday(string year)
        {
            //int year = DateTime.Now.Year;
            DateTime counYear = Convert.ToDateTime(year + "-01-01");
            DateTime nestYear = counYear.AddYears(1);
            List<PKHolidays> addList = new List<PKHolidays>(); // 新增
            List<PKHolidays> editList = new List<PKHolidays>(); // 更新
            for (DateTime i = counYear; i < nestYear; i = i.AddDays(1))
            {
                PKHolidays model = new PKHolidays();
                if ((int)i.DayOfWeek == 0 || (int)i.DayOfWeek == 6)
                {  // 周日
                    model.HolidayDate = i.ToString("yyyy-MM-dd");
                    var editdata = _db.Queryable<PKHolidays>().Where(t => t.HolidayDate == model.HolidayDate).First();
                    if (editdata == null)
                    {
                        model.HolidayDate = i.ToString("yyyy-MM-dd");
                        model.HolidayYear = i.Year;
                        model.HolidayMonth = i.Month;
                        model.Status = 1;
                        addList.Add(model);
                    }
                    else
                    {
                        model.HolidayDate = editdata.HolidayDate;
                        model.HolidayYear = i.Year;
                        model.HolidayMonth = i.Month;
                        model.Status = 1;
                        editList.Add(model);
                    }
                }
            }
            if (addList.Count > 0)
            {
                await _db.Insertable(addList).ExecuteCommandAsync();
            }
            if (editList.Count > 0)
            {
                await _db.Updateable(editList).ExecuteCommandAsync();
            }
        }

        #endregion
    }
}